PUBLISHED: Jan 30, 2019 2 min read

Handling Dates and Times with PHP

Handling dates correctly is important in our daily tasks. From querying databases to presenting and removing marketing banners. Today we’ll be going over how we handle timezone conversions and few quick examples to get you up and running quickly.

In this example we are converting a local timezone America/New_York to the UTC timezone. The first step is to instantiate the date using the DateTime object.

$date = new DateTime('2019-01-21 00:00:00', new DateTimeZone('America/New_York'));

The DateTime object can be instantiated with a formatted date and time string. To ensure the correct date object is created use the following format Y-m-d H:i:s when creating the object. It should be noted if the time is not present the object will use 00:00:00 as the time for the object.

To convert the date into the UTC timezone for storage or manipulating all we need to do is set the timezone on the object.

$date = new DateTime('2019-01-21 00:00:00', new DateTimeZone('America/New_York'));
$date->setTimeZone(new DateTimeZone('UTC')); // New timezone
echo $date->format('Y-m-d H:i:s e'); //2019-01-21 05:00:00 UTC

That’s really it with a few simple lines of code you can convert any date into UTC or any timezone anyone might need.