How to Easily Convert Dates from Utc via PHP

How can I easily convert dates from UTC via PHP?

Here's what we did with our servers. We set everything to use UTC, and we display in the user's time zone by converting from UTC on the fly. The code at the bottom of this post is an example of how to get this to work; you should confirm that it works in all cases with your setup (i.e. daylight savings, etc).

Configuring CentOS

  1. Edit /etc/sysconfig/clock and set ZONE to UTC
  2. ln -sf /usr/share/zoneinfo/UTC /etc/localtime

Configuring MySQL

  1. Import timezones into MySQL if necessary:

    mysql_tzinfo_to_sql /usr/share/zoneinfo | mysql -u root -p mysql

  2. Edit my.cnf and add the following within the [mysqld] section:

    default-time-zone = 'UTC'

PHP Code

<?php
/*
Example usage:
$unixtime = TimeUtil::dateTimeToTimestamp('2009-04-01 15:36:13');
echo TimeUtil::UTCToPST("M d, Y - H:i:s", $unixtime);
*/

// You should move this to your regular init method
date_default_timezone_set('UTC'); // make this match the server timezone

class TimeUtil {
public static function timestampToDateTime($timestamp) {
return gmdate('Y-m-d H:i:s', $timestamp);
}

public static function dateTimeToTimestamp($dateTime) {
// dateTimeToTimestamp expects MySQL format
// If it gets a fully numeric value, we'll assume it's a timestamp
// You can comment out this if block if you don't want this behavior
if(is_numeric($dateTime)) {
// You should probably log an error here
return $dateTime;
}
$date = new DateTime($dateTime);
$ret = $date->format('U');
return ($ret < 0 ? 0 : $ret);
}

public static function UTCToPST($format, $time) {
$dst = intval(date("I", $time));
$tzOffset = intval(date('Z', time()));
return date($format, $time + $tzOffset - 28800 + $dst * 3600);
}

}

Convert UTC dates to local time in PHP

date() and localtime() both use the local timezone for the server unless overridden; you can override the timezone used with date_default_timezone_set().

http://www.php.net/manual/en/function.date-default-timezone-set.php

http://us3.php.net/manual/en/function.date.php

http://php.net/manual/en/function.localtime.php

How to convert UTC datetime into PST datetime in php

Like this.

$utc_date = '2020-07-31T00:00:00.000Z';
$jsDateTS = strtotime($utc_date);
if ($jsDateTS !== false)
echo date('Y-m-d H:i:s', $jsDateTS );

Edit: Changed code to include timezone change.

$utc_date = '2020-07-31T00:00:00.000Z';
$timestamp = strtotime($utc_date);
$date = new DateTime();
$date->setTimestamp($timestamp);
$date->setTimezone(new \DateTimeZone('America/Los_Angeles'));
echo $date->format('Y-m-d H:i:s') . "\n";

Working Example.

php convert datetime to UTC

Try the getTimezone and setTimezone, see the example

(But this does use a Class)

UPDATE:

Without any classes you could try something like this:

$the_date = strtotime("2010-01-19 00:00:00");
echo(date_default_timezone_get() . "<br />");
echo(date("Y-d-mTG:i:sz",$the_date) . "<br />");
echo(date_default_timezone_set("UTC") . "<br />");
echo(date("Y-d-mTG:i:sz", $the_date) . "<br />");

NOTE: You might need to set the timezone back to the original as well

How to convert UTC timestamp Value to local date time

You need to change the timezone after to define the timestamp in GMT.

$timestamp = 1615958170523/1000;

$myDateTime = \DateTime::createFromFormat('U', (int)$timestamp);
echo $myDateTime->format('Y-m-d H:i:s'), PHP_EOL; // 2021-03-17 05:16:10

$myDateTime->setTimezone(new \DateTimeZone('Europe/Paris'));
echo $myDateTime->format('Y-m-d H:i:s'), PHP_EOL; // 2021-03-17 06:16:10

$myDateTime->setTimezone(new \DateTimeZone('America/Denver'));
echo $myDateTime->format('Y-m-d H:i:s'), PHP_EOL; // 2021-03-16 23:16:10

See DateTime::setTimezone() documentation

Parse a UTC date, output local datetime

You need to change the timezone of the date (using DateTime::setTimeZone()), not the default timezone:

date_default_timezone_set('UTC');
$dt = new DateTime("2021-03-31 23:46:14");
$dt->setTimeZone(new DateTimeZone("Europe/paris")); // change date timezone
echo $dt->format('m/d/Y, H:i:s');

Output:

04/01/2021, 01:46:14

Changing the default timezone affects the new DateTime(), not the format() result.

PHP convert UTC time to local time

The reason your code isn't working is most likely because your server is in UTC time. So the local time of the server is UTC.

Solution #1

One potential solution is to do the following server side and pass the epoch integer to the browser:

$utc = "2014-05-29T04:54:30.934Z";
$time = strtotime($utc); //returns an integer epoch time: 1401339270

Then use JavaScript to convert the epoch integer to the user's local time (the browser knows the user's timezone).

Solution #2

You can get the browser to send you the user's timezone. Then you can use this information to calculate the date string server side instead of browser side. See more here: https://stackoverflow.com/a/5607444/276949

This will give you the user's offset (-7 hours). You can use this information to set the timezone by looking here: Convert UTC offset to timezone or date

Convert date and time from UTC to client's local time on server with MYSQL

This is how I solved my issue with php.

The client gets the Timezone offset with javascript:

var date = new Date();
var utcOffset = -date.getTimezoneOffset()/60;

The client sends the offset to the server via ajax and the server fetches the offset:

$utcOffset = isset($_REQUEST["utcOffset"]) ? $_REQUEST["utcOffset"] : 0;
$pieces = explode(".", $utcOffset);
$hours = $pieces[0];

// handle '.5' because some timezones include a half hour portion
if (sizeof($pieces) == 1)
$minutes = 0;
else
$minutes = '.' . $pieces[1];

// convert .5 to 30
$minutes *= 60;

if ($hours[0] == '-')
$minutes = '-' . $minutes;

The server queries the database (this is shown in my original post). Then my php iterates through the results and produces xml, which is sent back to the client. Within that loop, I have placed this code, which converts the date and time from UTC to the client's local time:

$time = date('g:i a', strtotime($hours . ' hours,' . $minutes . ' minutes', strtotime(date($row['conditions_date'] . $row['conditions_time']))));

$date = date('D, M j, Y', strtotime($hours . ' hours,' . $minutes . ' minutes', strtotime(date($row['conditions_date'] . $row['conditions_time']))));

So in the database I have this date '2012-01-01' and this time '20:22:11'. The code above converts converts the time to '3:22 pm' and the date to 'Sun, Jan 1, 2012' when the client provides -5 (which is the value for Eastern Standard Time).

How to convert UTC datetime to another timezone?

Use DateTime and DateTimeZone.

$date = new DateTime('2012-07-16 01:00:00 +00');
$date->setTimezone(new DateTimeZone('Europe/Moscow')); // +04

echo $date->format('Y-m-d H:i:s'); // 2012-07-15 05:00:00


Related Topics



Leave a reply



Submit