PHP Split Date and Time
In order to split date and time or get one of these from the dateTime instance, we can use method called format()
. To get a dateTime instance in the first place, we can pass a string to the DateTime class.
If you haven't used DateTime class before, please check out how to Get UTC timestamp in PHP first. It has an example how to get current date/time and how to specify a time zone.
Don't try to attempt a manual string split (with hardcoded separators) as the format might differ a lot! Get the dateTime instance first.
Let's say that you have a dateTime string coming from an external source.
$dateTimeString = "1999-12-30 9:30:15 AM";
// Get date time instance
$dateTime = new \DateTime($dateTimeString);
print_r($dateTime)
/* ๐๏ธ DateTime Object
(
[date] => 1999-12-30 09:30:15.000000
[timezone_type] => 3
[timezone] => UTC
)
*/
Now that we have a dateTime instance, we can call format() method on it.
$out = $dateTime->format('Y-m-d H:i:s');
print_r($out)
// ๐๏ธ 1999-12-30 09:30:15
To get date or time or both as separate variables from the string, you have various options. If you need both date and time but have them separated, you can either call format() twice or split string with built-in method.
$date = $dateTime->format('Y-m-d');
print_r($date);
// ๐๏ธ 1999-12-30
$time = $dateTime->format('H:i:s');
print_r($time);
// ๐๏ธ 09:30:15
As mentioned, another way to split date and time is to call format() once and then split string by using built-in explode() method.
$str = $dateTime->format('Y-m-d H:i:s');
$out = explode(' ', $str);
print_r($out);
/* ๐๏ธ Array
(
[0] => 1999-12-30
[1] => 09:30:15
)
*/
In the example above we only needed to call format() once, although the previous example is a bit more explicit.
When using DateTime, you can pass a second parameter which represents the timezone. As mentioned, feel free to check Get UTC timestamp in PHP post to see how to specify timezone.
When you pass an instance of DateTimeZone with UTC timezone to the DateTime as second param, you'll always get the same (utc) timestamp no matter the timezone you're currently in.
GMT and UTC share the same current time, so what's the difference between these two?
In a nutshell, GMT is a time zone and UTC is a time standard. In fact, UTC is the standard for time zones worldwide.