Convert datetime UTC to local time in PHP - php

I have two pieces of data being returned in JSON:
"startTimeUTC":"2018-07-03T21:00:00.000Z"
"siteTimeZone":-4.0"
I am then doing this in PHP:
$start = date_format(date_create($event['startTimeUTC']), 'Y-m-d h:i:s');
Which returns this:
2018-07-03 09:00:00
I am not sure how I subtract the timezone offset from the original time.
The expected time should be: 05:00:00 PM
I have tried so many different things to get this to work, but have had no luck.
How do I get the correct time to convert to the local time based on the timezone offset?

The date string already contains the Zulu timezone. So you need to create a new DateTime object, and then set the new timezone afterwards.
$date = new Datetime('2018-07-03T21:00:00.000Z');
$date->setTimezone(new DateTimeZone('-4.0'));
var_dump($date->format('Y-m-d H:i:s')); // 2018-07-03 17:00:00

You can use the timezone as a multiplier to add/subtract from the UTC time.
// convert your time via `strtotime` and then add your offset * 3600 (seconds in an hour)
$start = date('Y-m-d h:i:s',strtotime($event['startTimeUTC']) + ($event['siteTimeZone'] * 3600)) ;

Related

Convert PHP Mongo UTC Date From Milliseconds To Date for TimeZone

I have a date in UTC / Epoch format from a mongo database (1659052800000) and I'm trying to convert it to a friendly format using PHP for the PST timezone.
Here's what I've tried.
date_default_timezone_set('PST');
$this->vars[dateOfEvent] = date('Y-m-d', 1659052800000);
and
date_default_timezone_set('PST');
$dt = new DateTime(1659052800000);
$this->vars[dateOfEvent] = $dt->format('Y-m-d');
but neither give me the correct date. I'm expecting it to out "2022-07-28"
You can set the timezone temporarily for the DateTime object. Also you need to set timestamp divided by 1000 or remove the last three zeroes.
$dt = new DateTime();
$dt->setTimestamp(1659052800000 / 1000);
$dt->setTimezone(new DateTimeZone('PST'));
echo $dt->format('Y-m-d');
prints
2022-07-28

How do I convert date of format like /Date(1490914800000+0100)/ to mysql datetime format in php?

I have tried to solve it by extracting the numeric part and then parsed it using date function. But it shows me some old date which I guess is not correct.
$datef = "1490914800000+0100";
$adada = date('Y-m-d H:i:s', $datef);
// Gives date 1987-10-13 18:31:28 which is an old date. Please suggest.
One approach, well-covered by this SO question, is to use the DateTime() function to convert time in seconds since epoch to a date, and then display this date using format(). But there are two caveats with your data. First, you appear to have milliseconds since the epoch, which needs to be converted to seconds. Second, you also have a timezone shift, in hours, tagged to the end. I split your $datef string into two parts, epoch and timezone, then arrive at the number of seconds since epoch.
list($epoch, $timezone) = explode('+', $datef);
$epoch = ($epoch / 1000) + (substr($timezone, 0, 2)*60*60) +
(substr($timezone, 2, 2)*60);
$dt = new DateTime("#$epoch");
echo $dt->format('Y-m-d H:i:s');
Output:
2017-03-31 00:00:00
Demo here:
PHP Sandbox
The time seems to be in milliseconds.
You can add the timezone shift to the seconds. 1 hour = 3600 seconds.
$milliSeconds = intval("1490914800000");
$seconds = $milliSeconds/1000;
$date = date("Y-m-d H:i:s", $seconds);

PHP timestamps & timezone configuration

My plan:
Get the current timestamp using strtotime("now")
Convert that to timezone '0' - This is the part I don't know how to do. I have the number that represents the users timezone, like -8 hours for example.
Store it in the database in timezone '0'
Retrieve it from the database in timezone '0'
Convert it to the users timezone in the opposite direction
use the date('', timestamp) function to display it
How can I accomplish the conversion? Or am I going about this wrong?
I need to be able to store it in the database as a numerically represented time (like strtotime returns)
Using time() is the same as strtotime("now") and you do not need to worry about converting the timezone of the timestamp, as the timestamp has no timezone:
Does PHP time() return a GMT/UTC Timestamp?
time returns a UNIX timestamp, which is timezone independent. Since
a UNIX timestamp denotes the seconds since 1970 UTC you could say it's
UTC, but it really has no timezone.
You can then store that timestamp in your database. When you retrieve it you can convert it to the users timezone. With something like this:
date_default_timezone_set('UTC');
$timestamp = '1429066967';
//Supported Timezones: http://php.net/manual/en/timezones.php
$userTimezone = 'America/Los_Angeles';
$dt = new DateTime();
// Set the timestamp
$dt->setTimestamp($timestamp);
// Set the timezone
$dt->setTimezone(new DateTimeZone($userTimezone));
// Format the date
$date = $dt->format('Y-m-d H:i:s');
echo $date;
Outputs: 2015-04-14 20:02:47
But if you only have the UTC offset you could try this:
date_default_timezone_set('UTC');
$timestamp = '1429066967';
$offset = -8;
$userTimezone = timezone_name_from_abbr("", $offset*3600, false);
$dt = new DateTime();
// Set the timestamp
$dt->setTimestamp($timestamp);
// Set the timezone
$dt->setTimezone(new DateTimeZone($userTimezone));
// Format the date
$date = $dt->format('Y-m-d H:i:s');
echo $date;
Which also outputs: 2015-04-14 20:02:47

strtotime is different with timezone

Seems I don't quite understand much the function strtotime. My case is I would like to compare the current time (now) with a specific time on specific timezone
For example the specific time is "this Monday at 14:00:00" at the timezone "America/New_York":
$specificTime = strtotime("monday this week 14:00:00 America/New_York");
My current code is:
$now = strtotime("now America/New_York");
if ($now > $specificTime) {
//do something
}
But I have figured it out that $now above is 6 hours ahead with current time. The number 6 I guess from offset -05:00 of America/New_York, plus with 1 hour daylight saving.
it should remove timezone out of $now, it will work correctly:
$now = strtotime("now");
if ($now > $specificTime) {
//do something
}
Could someone give the explain why strtotime("now America/New_York") is 6 hours ahead with strtotime("now), why they are not equivalent? really confused.
P.S: I am on GMT+07:00.
Simple debugging:
<?php
$now = strtotime("now America/New_York");
echo date('r', $now);
// Thu, 28 Nov 2013 16:39:51 +0100
... shows that such command is doing this:
Calculate local time in my default time zone (10:39:51 +0100)
Return timestamp that corresponds to 10:39:51 in New York time (-0500)
Doing date manipulation with strings is terribly complicated. Just imagine you'd try to do math with string functions: strtofloat('one plus square root of half hundred')—there'd be plenty of room for mistakes. So my advise is to keep it simple and only use with simple expressions when there's some benefit, such as strtotime('+1 day').
If you need to work with different time zones, I suggest you use proper DateTime objects. If you choose to work with Unix timestamps, forget about time zones: Unix timestamps do not have time zone information at all.
You can use DateTime for this. I believe settings a timezone in strtotime is not valid.
$specificTime = new DateTime("monday this week 14:00:00", new DateTimeZone("America/New_York")));
$now = new DateTime("now", new DateTimeZone("America/New_York"));
You can then compare unix timestamp with this:
if ($now->getTimestamp() > $specificTime->getTimestamp()) {
// do something ...
}
There is time offset between each timezone.
strtotime() function will return the Unix timestamp according the timezone.
It will use the default time zone unless a time zone is specified in that parameter.
The default time zone it the return value of date_default_timezone_get();
Look the code below:
<?php
// UTC
echo date_default_timezone_get(), "\n";
// 2013-11-28 14:41:37
echo date('Y-m-d H:i:s', strtotime("now America/New_York")), "\n";
// 2013-11-28 09:41:37
echo date('Y-m-d H:i:s', strtotime("now")), "\n";

There is a simple way to get unix time range of a day if given a random timestamp from that day?

There is a simple way to get unix time range of a day if given a random timestamp from that day ?
I have a date like 1345547471 which is "Tue, 21 Aug 2012 11:11:11 GMT"
There is a php function that can receive a timestamp like this and return a 00:00 hours timestamp and a 23:59 hours timestamp of that day ?
Thank you.
Sure, DateTime can do that:
$time = 1345547471;
$date = new DateTime;
// $date->setTimezone( new DateTimeZone( "America/New_York")); // Can set TZ here if needed
$date->setTimestamp( $time);
Now, you can set the time to whatever you want:
$date->setTime( 0, 0, 0); // 0h 0m 0s
And grab the resulting UNIX Timestamp:
$timestamp = $date->getTimestamp();
Same thing for the next use-case:
$date->setTime( 23, 59, 0);
$timestamp = $date->getTimestamp();
It is important to note that DateTime will properly handle cases of daylight savings time and local time discontinuities.
You can use the mod (gives the remainder after a division) PHP function like this to get the first second of a Unix timestamp (ie, today 0:00:00)
$var=time()-(time()%86400);
Then with this unix timstamp, you can add 86399 to get the last second of the day.
Edit: This doesn't account for dalylight savings.
$ts = 1345547471;
$ts_00_00 = mktime(0,0,0, date("m", $ts), date("d",$ts), date("Y",$ts);
$ts_23_59 = mktime(23,59,59, date("m", $ts), date("d",$ts), date("Y",$ts);
Documentation:
http://php.net/manual/en/function.date.php
http://php.net/manual/en/function.mktime.php
If you are using PHP >= 5.3.0 Then you can use this...
Check out for this.
http://www.php.net/manual/en/datetime.createfromformat.php
This is similar to Fluffeh's answer, but accounts for daylight savings time. This is based on the server's time zone.
//Get time range for today
$start = strtotime(date("Y-m-d")." 00:00:00");
$end = strtotime(date("Y-m-d")." 23:59:59");
//Show our date in a human-readable format for troubleshooting
echo date(DATE_RFC1036,$start)."<br>".date(DATE_RFC1036,$end);
If you want to specify a custom timezone instead of the server timezine, you can add it to like so:
//Get time range for today
$start = strtotime(date("Y-m-d")." 00:00:00 -0500");
$end = strtotime(date("Y-m-d")." 23:59:59 -0500");
//Show our date in a human-readable format for troubleshooting
echo date(DATE_RFC1036,$start)."<br>".date(DATE_RFC1036,$end);
Link to working Sample

Categories