receiving time stamp in another timezone - php

may be you know why this doesnt work (trying to receive timeStamp in another timeZone):
$from_zone = 'Europe/Kiev';
$to_zone = 'US/Eastern';
$stamp = 1383897599;
$from_tz = new DateTimeZone($from_zone);
$to_tz = new DateTimeZone($to_zone);
$dateTime = new DateTime(null, $from_tz);
$dateTime->setTimestamp($stamp);
$dateTime->setTimeZone($to_tz);
$new_stamp = $dateTime->getTimestamp();
echo $new_stamp;
return initial timeStamp instead of the new one, what im doing wrong ? :\

UNIX timestamps are by definition based on UTC. A timestamp will always return same date/time regardless of time zone.
From Wikipedia:
Unix time, or POSIX time, is a system for describing instants in time, defined as the number of seconds elapsed since midnight Coordinated Universal Time (UTC) of Thursday, January 1, 1970

Timestamp is a number of seconds passed since 1 January 1970 00:00:00 UTC. Changing timezones does not affect that value, as well as time() function returns the same value independently of the set timezone.
If you need different timestamps, try using strtotime($dateString), as it is affected by timezones, like this:
date_default_timezone_set('Europe/Kiev');
$date = date('Y-m-d H:i:s');
echo $date . ' - ' . strtotime($date) . '<br />';
date_default_timezone_set('US/Eastern');
echo $date . ' - ' . strtotime($date) . '<br />';
which prints:
2013-11-08 20:48:47 - 1383936527
2013-11-08 20:48:47 - 1383961727

Related

I want to count "hours into a month" in php

The following code helps me project data from a database onto our internal adminsite for the current day.
Since we're in multiple time zones, we use UTC time for basic time function, but since our office is in California, we want the date to actually be = ($date)'hours' - 8, because PST is 8 hours behind.
We use the following logic to show the "previous day" if it's "a day ahead" UTC time but the same day our time, which works great, however, on the last day of the month at 4 PM, all of our data is hidden.
<?php
$date = getDate();
if ($date['hours'] < 8) {
$dateDay = $date['mday']-1;
} else {
$dateDay = $date['mday'];
}
$dateMonth = $date['mon'];
// last day of month
// $dateMonth = $date['mon'] - 1;
$dateYear = $date['year'];
$dateTime = $dateYear . "-" . $dateMonth . '-' . $dateDay . ' 08:00:00';
So, this 'if' function works great to show the true "day." What it says is, if the UTC hour < 8, then it's actually yesterday, as 3 AM UTC time is actually 7 PM the day before PST.
What I was wondering is if there's a way to track "month hours", so I could use the same 'if' function that reads "if we're less than 8 UTC hours into the month, it's actually still last month."
That way it'll work regardless of whether the month has 28, 30 , or 31 days. Does such logic exist?
I think its the best way to deal with it :
<?php
$date = new DateTime('2016-08-08', new DateTimeZone('UTC'));
echo $date->format('Y-m-d H:i:sP') . "\n";
$date->setTimezone(new DateTimeZone('America/Los_Angeles'));
echo $date->format('Y-m-d H:i:sP') . "\n";
?>
You can use DateTime::sub or DateTime::modify method which will keep correct month for you:
$now = new DateTime(getDay()); // supposing getDate() returns something that can be parsed with DateTime constructor
// Unless using DateTimeImmutable, cloning is needed to prevent altering the original object
$min = clone ($now);
$min->modify('-8 hours');
// alternatively $min->sub(new DateInterval('PT8H'));
if ($now->format('m') !== $min->format('m')) {
// month differs
}

date returning different results in different versions of php

I have a date A and B.
I wanted to get the hours/minutes between them. Like:
date('h:i', strtotime(B) - strtotime(A));
But I get strange results:
echo date('h:i', strtotime('2014-01-01') - strtotime('2014-01-01'));
// echoes: 01:00 (!)
date_default_timezone_set('Europe/London');
$date = new DateTime();
$A = $date->format('Y-m-d H:i:s'); echo '<br />';
$date->modify("+64 minutes");
$B = $date->format('Y-m-d H:i:s'); echo '<br />';
echo date('h:i', strtotime($B) - strtotime($A));
// echoes 02:04 (!)
Live example for the previous code:
Why is this and how to get the expected result?
This is correct behavior
Why? Think of it: strtotime('2014-01-01') - strtotime('2014-01-01') is zero - but date() expects timestamp as second parameter. So that means, you're trying to get date from zero-point timestamp. And that point is different in different timezones. Your London TZ has +01 offset, that's why 0-point timestamp is 01 Jan 1970 01:00:00 - and that's why date('h:i', 0) is 01:00
Try to set, for example, Moscow zone:
date_default_timezone_set('Europe/Moscow');
$date = new DateTime();
$A = $date->format('Y-m-d H:i:s');
$date->modify("+64 minutes");
$B = $date->format('Y-m-d H:i:s');
echo date('h:i', strtotime($B) - strtotime($A));//04:04
-you'll see exactly 04:04 - because current offset for Moscow is +03 (so 03 hours + 64 minutes modification)
What date expects as its second parameter is an absolute timestamp, which it then formats in the specified format. You outputting h:i means you're outputting only the hour:minute part of a complete year, month, day, hour, minute, second timestamp. If you want to format the relative difference between two timestamps, date is the wrong function to use. The result is expected, since you're actually dealing with absolute timestamps in timezones.

How to store expiration time?

I want to store the expiration time in database. I am using the below code to store expiration time with +1 year.
$cdate = time();
$date = $cdate + 365*24*60*60;
$date = date("Y-m-d H:i:s",$date);
but its not storing the correct time it stores 2014-08-10 07:55:14 but time on storing is 2014-08-10 01:25:14.
Aslo not sure its Am or Pm .
Thanks.
Time/date functions in PHP are using timezones to determine your local time. So if your server is in timezone GMT+6 that means that the date() function will return you the date/time that is 6 hours before GMT.
You can check the date_default_timezone_set() function manual to find out how PHP is selecting your timezone.
To set your timezone, you can use date_default_timezone_set() before calling date function or you can set you php.ini setting date.timezone to your timezone.
For the second part of your question - when formatting time using the date() function the H format character will return 24-hour format of an hour with leading zeros.
try this
<?php
$timezone1 = "America/Los_Angeles";
date_default_timezone_set($timezone1);
$cdate = time();
$date1 = $cdate + 365*24*60*60;
$date = date("Y-m-d H:i:s a",$date1);
echo $date;
$timezone = "Asia/Calcutta";
date_default_timezone_set($timezone);
$cdate = time();
$date1 = $cdate + 365*24*60*60;
$date = date("Y-m-d H:i:s a",$date1);
echo $date;
?>
you can set timezone for your location.And also refer this codepad-FIDDLE
As others have mentioned, it is calculating the time based on your server (local) time.
I suggest you store the time in GMT and then adjust it to your desired timezone as necessary.
You can use strtotime() to calculate 1 year from now (no need to calculate it yourself) and use gmdate() to get the timestamp in GMT.
echo "Next Year in local time: ". date("Y-m-d H:i:s", strtotime("+1 year")) ."\n";
echo "Next year in GMT: " . gmdate ("Y-m-d H:i:s", strtotime ("+1 year")) . "\n";
// Output:
// Next Year in local time: 2014-08-10 15:25:09
// Next year in GMT: 2014-08-10 08:25:09

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

Strange behavior of PHP time math: Why is strtotime() returning negative numbers?

I'm trying to do some very basic time math - basically, given inputs of time and distance, calculate the speed. I chose to use strtotime() to convert the time inputs into seconds - but I'm getting some bizarre results.
For example, given this sample program:
<?php
$t1 = strtotime("3:15:00",0);
$t2 = strtotime("1:00:00",0);
$t3 = strtotime("2:00:00",0);
$t4 = strtotime("9:00:00",0);
echo $t1 . "\n";
echo $t2 . "\n";
echo $t3 . "\n";
echo $t4 . "\n";
?>
Why do I get these results?
$ php test.php
-56700
-64800
-61200
-36000
Update:
Since no one said it explicitly, let me explain the bug in the above function. I had assumed that passing a time of zero to strtotime() would cause it to generate time stamps derived from midnight, 12/31/1969, UTC - which sounds odd, but would work for my purposes.
What I hadn't counted on was that strtotime() takes time zones into account when converting strings, and my server is apparently 5 hours behind UTC. On top of that, because of the time zone shift, PHP then interprets the times as relative to the day before the epoch which means it is interpreting my times as occurring relative to December 30th, 1969 instead of the 31st, resulting in negative numbers...
It appears that Eugene is correct - if I want to calculate just the elapsed time, I can't use the built in time functions.
If you want to do something like that, I think you want to just do some math on the time strings themselves and convert them to a number of seconds, like this:
<?php
function hmstotime($hms)
{
list($hours, $minutes, $seconds) = explode(":",$hms);
return $hours * 60 * 60 + $minutes * 60 + $seconds;
}
?>
Apparently with just bare times PHP is assigning the date December 31, 1969. When I ran this:
echo date('F j, Y H:i:s', $t1) . "\n";
echo date('F j, Y H:i:s', $t2) . "\n";
echo date('F j, Y H:i:s', $t3) . "\n";
echo date('F j, Y H:i:s', $t4) . "\n";
I got this:
December 31, 1969 03:15:00
December 31, 1969 01:00:00
December 31, 1969 02:00:00
December 31, 1969 09:00:00
Remember that strtotime returns a UNIX timestamp, which is defined as the number of seconds since January 1, 1970. By definition a UNIX timestamp refers to a specific month/day/year, so despite the name strtotime is not really intended for bare times without dates.
Because strtotime() outputs the number of seconds relative to the second argument (in your case, the Unix epoch (December 31, 1969 19:00:00)).
The negative numbers is expected because "3:15:00" is 56700 seconds before the Unix epoch.
Try it without the second parameter. That's supposed to be a timestamp for the returned time to be relative to. Giving it 0 means you're asking for a timestamp relative to the Unix epoch.
In response to your comment:
It's not documented functionality, but I use strtotime("HH:MM") all the time, and it returns a timestamp relative to the current time. I guess if you want to be sure though, you could do this:
strtotime("3:15:00",time());
strtotime() without a second argument gets the time from the supplied string and fills in the blanks from the current date:
echo date('Y-m-d H:i:s', strtotime("3:15:00"));
-> 2009-06-30 03:15:00
With a second argument it calculates the date relative to the second argument:
echo date('Y-m-d H:i:s', strtotime("3:15:00", 0));
-> 1970-01-01 03:15:00
To calculate the difference between two timestamps in seconds, you can just do this:
echo strtotime("3:15:00") - strtotime("3:00:00");
-> 900
Edit: Of course taking into account which is the bigger number:
$t1 = strtotime("3:15:00");
$t2 = strtotime("3:30:00");
$diff = max($t1, $t2) - min($t1, $t2);
$diff = abs($t1 - $t2);
Or something of that nature...

Categories