I have already read How to get local time in php? and similar questions, but here I want to do the contrary:
With a given datetime in UTC (e.g. 2021-03-31 23:45:00), how to output the date in local timezone?
$dt = new DateTime("2021-03-31 23:45:00"); // parse the UTC datetime
echo $dt->format('m/d/Y, H:i:s');
In Europe/Paris timezone, it should output 2021-04-01 01:45:00, but here it sill outputs 2021-03-31 23:45:00. How to fix this?
I also tried with strtotime with a similar result; I also tried with:
date_default_timezone_set('UTC');
$dt = new DateTime("2021-03-31 23:46:14");
date_default_timezone_set('Europe/Paris');
echo $dt->format('m/d/Y, H:i:s');
without success.
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.
This can also be easily solved with date and strtotime:
//The following line is only required if the server has a different time zone.
//date_default_timezone_set('Europe/Paris');
$utcDate = "2021-03-31 23:45:00";
echo date('m/d/Y, H:i:s',strtotime($utcDate.' UTC'));
Output:
04/01/2021, 01:45:00
i am trying to get the correct time with php
not the one that the user's computer gives is there a function that gives the correct "GMT" time as an example .
PHP gets the server date, not the user computer date.
If you need to get a different date timezone then you need set the timezone to your desired.
See: http://php.net/manual/en/function.date.php
like:
$tz = 'Europe/London';
$timestamp = time();
$dt = new DateTime("now", new DateTimeZone($tz)); //first argument "must" be a string
$dt->setTimestamp($timestamp); //adjust the object to correct timestamp
echo $dt->format('d.m.Y, H:i:s');
If you just want GMT time, you can use gmdate instead of date. For example,
echo date('Y-m-d H:i:s') . "\n";
echo gmdate('Y-m-d H:i:s') . "\n";
Output (for a server in Europe)
2019-02-04 03:34:05
2019-02-04 02:34:05
Demo on 3v4l.org
You will be getting the server time only, not the computer time
$now = new DateTime(null, new DateTimeZone('America/New_York')); //timezone format
echo $now->format("Y-m-d\TH:i:sO"); // Server time
My code assumes that zero represents the beginning of the Unix epoch, 1970-01-01 00:00. I upgraded an installation of PHP and now, all of a sudden, zero represents 1970-01-01 01:00 (as verified with date('Y-m-d H:i', 0)). So apparently there is a time zone matter. I put the same code into a sandbox and got 1969-12-31 16:00. I have several unit tests that are broken as a result of this. Time zones do not and should not come into play here.
How can I ensure that date-time functions such as date() always converts zero to 1970-01-01 00:00 regardless of the time zone setting on the particular installation?
Using gmdate() you'll always get 1970-01-01 00:00 for 0, no matter what timezone your server is in:
<?php
date_default_timezone_set('Europe/Berlin');
echo "Europe/Berlin:\n";
echo "gmdate: ".gmdate('d.m.y H:i', 0) . "\n";
echo "date: ".date('d.m.y H:i', 0) . "\n";
date_default_timezone_set('America/Los_Angeles');
echo "\nAmerica/Los_Angeles:\n";
echo "gmdate: ".gmdate('d.m.y H:i', 0) . "\n";
echo "date: ".date('d.m.y H:i', 0) . "\n";
/* OUTPUT:
Europe/Berlin:
gmdate: 01.01.70 00:00
date: 01.01.70 01:00
America/Los_Angeles:
gmdate: 01.01.70 00:00
date: 31.12.69 16:00
*/
https://3v4l.org/FechC
You need to set the default time zone to GMT if you want to use date() like that. For example:
date_default_timezone_set('GMT');
echo date('Y-m-d H:i [I] [e] [O]',0);
The above will show (no matter what the server has been set to):
1970-01-01 00:00 [0] [GMT] [+0000]
Without the date_default_timezone_set('GMT'), or even set to Europe/London, you will get a different result at different times of the year.
From the PHP manual;
date — Format a local time/date
gmdate — Format a GMT/UTC date/time
The solution is to get the timezone setting, set it aside, change the timezone to UTC, perform the calculations, and reset the timezone to its original setting.
So if my original function looked like this:
public function format($argument = null)
{
// Perform some calculations involving date() and strtotime().
return $result;
}
Now it looks like this:
public function format($argument = null)
{
$timezone = date_default_timezone_get();
date_default_timezone_set('UTC');
$result = ...; // Perform some calculations involving date() and strtotime().
date_default_timezone_set($timezone);
return $result;
}
I have a website which displays dates from database using date() function. Now I have to add support for various timezones. Time needs to be changed only for display purposes in the front end. I used date_default_timezone_set('Europe/London'), but it did not affect the date output - it stays the same as in the database. Function date_default_timezone_get() shows that the timezone is set successfully, but the date output stays the same. How can I change the global output of date? Can it be done without editing all the date() functions in the site?
Full example:
date_default_timezone_set('Europe/London');
echo date_default_timezone_get(); //shows Europe/London
$date_from_db = '2014-02-02 12:34:05'; //this is generally taken from database
echo date('Y-m-d H:i:s',strtotime($date_from_db));
Outputs the same as before.
If your dates are stored in GMT, you can let strtotime() know by appending the timezone:
echo date('Y-m-d H:i:s', strtotime("$date_from_db GMT"));
Of course, setting Europe/London as the timezone, the results are likely the same.
Or, in your case:
echo date('Y-m-d H:i:s', strtotime("$date_from_db +0100"));
// 2014-02-02 11:34:05
Try to use DateTime class - see examples on this page http://www.php.net/manual/en/datetime.settimezone.php
<?php
$date = new DateTime('2000-01-01', new DateTimeZone('Pacific/Nauru'));
echo $date->format('Y-m-d H:i:sP') . "\n";
$date->setTimezone(new DateTimeZone('Pacific/Chatham'));
echo $date->format('Y-m-d H:i:sP') . "\n";
?>
I am in need of an easy way to convert a date time stamp to UTC (from whatever timezone the server is in) HOPEFULLY without using any libraries.
Use strtotime to generate a timestamp from the given string (interpreted as local time) and use gmdate to get it as a formatted UTC date back.
Example
As requested, here’s a simple example:
echo gmdate('d.m.Y H:i', strtotime('2012-06-28 23:55'));
Using DateTime:
$given = new DateTime("2014-12-12 14:18:00");
echo $given->format("Y-m-d H:i:s e") . "\n"; // 2014-12-12 14:18:00 Asia/Bangkok
$given->setTimezone(new DateTimeZone("UTC"));
echo $given->format("Y-m-d H:i:s e") . "\n"; // 2014-12-12 07:18:00 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
Do this way:
gmdate('Y-m-d H:i:s', $timestamp)
or simply
gmdate('Y-m-d H:i:s')
to get "NOW" in UTC.
Check the reference:
http://www.php.net/manual/en/function.gmdate.php
If you have a date in this format YYYY-MM-HH dd:mm:ss,
you can actually trick php by adding a UTC at the end of your "datetime string" and use strtotime to convert it.
date_default_timezone_set('Europe/Stockholm');
print date('Y-m-d H:i:s',strtotime("2009-01-01 12:00"." UTC"))."\n";
print date('Y-m-d H:i:s',strtotime("2009-06-01 12:00"." UTC"))."\n";
This will print this:
2009-01-01 13:00:00
2009-06-01 14:00:00
And as you can see it takes care of the daylight savings time problem as well.
A little strange way to solve it.... :)
Convert local time zone string to UTC string.
e.g. New Zealand Time Zone
$datetime = "2016-02-01 00:00:01";
$given = new DateTime($datetime, new DateTimeZone("Pacific/Auckland"));
$given->setTimezone(new DateTimeZone("UTC"));
$output = $given->format("Y-m-d H:i:s");
echo ($output);
NZDT: UTC+13:00
if $datetime = "2016-02-01 00:00:01", $output = "2016-01-31 11:00:01";
if $datetime = "2016-02-29 23:59:59", $output = "2016-02-29 10:59:59";
NZST: UTC+12:00
if $datetime = "2016-05-01 00:00:01", $output = "2016-04-30 12:00:01";
if $datetime = "2016-05-31 23:59:59", $output = "2016-05-31 11:59:59";
https://en.wikipedia.org/wiki/Time_in_New_Zealand
If you don't mind using PHP's DateTime class, which has been available since PHP 5.2.0, then there are several scenarios that might fit your situation:
If you have a $givenDt DateTime object that you want to convert to UTC then this will convert it to UTC:
$givenDt->setTimezone(new DateTimeZone('UTC'));
If you need the original $givenDt later, you might alternatively want to clone the given DateTime object before conversion of the cloned object:
$utcDt = clone $givenDt;
$utcDt->setTimezone(new DateTimeZone('UTC'));
If you only have a datetime string, e.g. $givenStr = '2018-12-17 10:47:12', then you first create a datetime object, and then convert it. Note this assumes that $givenStr is in PHP's configured timezone.
$utcDt = (new DateTime($givenStr))->setTimezone(new DateTimeZone('UTC'));
If the given datetime string is in some timezone different from the one in your PHP configuration, then create the datetime object by supplying the correct timezone (see the list of timezones PHP supports). In this example we assume the local timezone in Amsterdam:
$givenDt = new DateTime($givenStr, new DateTimeZone('Europe/Amsterdam'));
$givenDt->setTimezone(new DateTimeZone('UTC'));
As strtotime requires specific input format, DateTime::createFromFormat could be used (php 5.3+ is required)
// set timezone to user timezone
date_default_timezone_set($str_user_timezone);
// create date object using any given format
$date = DateTime::createFromFormat($str_user_dateformat, $str_user_datetime);
// convert given datetime to safe format for strtotime
$str_user_datetime = $date->format('Y-m-d H:i:s');
// convert to UTC
$str_UTC_datetime = gmdate($str_server_dateformat, strtotime($str_user_datetime));
// return timezone to server default
date_default_timezone_set($str_server_timezone);
I sometime use this method:
// It is not importnat what timezone your system is set to.
// Get the UTC offset in seconds:
$offset = date("Z");
// Then subtract if from your original timestamp:
$utc_time = date("Y-m-d H:i:s", strtotime($original_time." -".$offset." Seconds"));
Works all MOST of the time.
http://php.net/manual/en/function.strtotime.php or if you need to not use a string but time components instead, then http://us.php.net/manual/en/function.mktime.php
With PHP 5 or superior, you may use datetime::format function (see documentation http://us.php.net/manual/en/datetime.format.php)
echo strftime( '%e %B %Y' ,
date_create_from_format('Y-d-m G:i:s', '2012-04-05 11:55:21')->format('U')
); // 4 May 2012
try
echo date('F d Y', strtotime('2010-01-19 00:00:00'));
will output:
January 19 2010
you should change format time to see other output
General purpose normalisation function to format any timestamp from any timezone to other.
Very useful for storing datetimestamps of users from different timezones in a relational database. For database comparisons store timestamp as UTC and use with gmdate('Y-m-d H:i:s')
/**
* Convert Datetime from any given olsonzone to other.
* #return datetime in user specified format
*/
function datetimeconv($datetime, $from, $to)
{
try {
if ($from['localeFormat'] != 'Y-m-d H:i:s') {
$datetime = DateTime::createFromFormat($from['localeFormat'], $datetime)->format('Y-m-d H:i:s');
}
$datetime = new DateTime($datetime, new DateTimeZone($from['olsonZone']));
$datetime->setTimeZone(new DateTimeZone($to['olsonZone']));
return $datetime->format($to['localeFormat']);
} catch (\Exception $e) {
return null;
}
}
Usage:
$from = ['localeFormat' => "d/m/Y H:i A", 'olsonZone' => 'Asia/Calcutta'];
$to = ['localeFormat' => "Y-m-d H:i:s", 'olsonZone' => 'UTC'];
datetimeconv("14/05/1986 10:45 PM", $from, $to); // returns "1986-05-14 17:15:00"
As an improvement on Phill Pafford's answer (I did not understand his 'Y-d-mTG:i:sz' and he suggested to revert timezone).
So I propose this (I complicated by changing the HMTL format in plain/text...):
<?php
header('content-type: text/plain;');
$my_timestamp = strtotime("2010-01-19 00:00:00");
// stores timezone
$my_timezone = date_default_timezone_get();
echo date(DATE_ATOM, $my_timestamp)."\t ($my_timezone date)\n";
// changes timezone
date_default_timezone_set("UTC");
echo date("Y-m-d\TH:i:s\Z", $my_timestamp)."\t\t (ISO8601 UTC date)\n";
echo date("Y-m-d H:i:s", $my_timestamp)."\t\t (your UTC date)\n";
// reverts change
date_default_timezone_set($my_timezone);
echo date(DATE_ATOM, $my_timestamp)."\t ($my_timezone date is back)\n";
?>
alternatively you can try this:
<?php echo (new DateTime("now", new DateTimeZone('Asia/Singapore')))->format("Y-m-d H:i:s e"); ?>
this will output :
2017-10-25 17:13:20 Asia/Singapore
you can use this inside the value attribute of a text input box if you only want to display a read-only date.
remove the 'e' if you do not wish to show your region/country.
Follow these steps to get UTC time of any timezone set in user's local system (This will be required for web applications to save different timezones to UTC):
Javascript (client-side):
var dateVar = new Date();
var offset = dateVar.getTimezoneOffset();
//getTimezoneOffset - returns the timezone difference between UTC and Local Time
document.cookie = "offset="+offset;
Php (server-side):
public function convert_utc_time($date)
{
$time_difference = isset($_COOKIE['offset'])?$_COOKIE['offset']:'';
if($time_difference != ''){
$time = strtotime($date);
$time = $time + ($time_difference*60); //minutes * 60 seconds
$date = date("Y-m-d H:i:s", $time);
} //on failure of js, default timezone is set as UTC below
return $date;
}
..
..
//in my function
$timezone = 'UTC';
$date = $this->convert_utc_time($post_date); //$post_date('Y-m-d H:i:s')
echo strtotime($date. ' '. $timezone)