Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Unix timestamp in php based on timezone

Tags:

Code first

    echo time() . '<br/>'; echo date('Y-m-d H:i:s') . '<br/>'; date_default_timezone_set('America/New_York');   echo time() . '<br/>'; print_r($timezones[$timezone] . '<br/>'); echo date('Y-m-d H:i:s') . '<br/>'; 

In the above code the date is printed according to timezone but unix timestamp is same even after setting default timezone

How can we print unix timestamp according to timezone?

like image 275
jimy Avatar asked Dec 29 '11 12:12

jimy


2 Answers

The answer provided by Volkerk (that says timestamps are meant to be always UTC based) is correct, but if you really need a workaround (to make timezone based timestamps) look at my example.

<?php  //default timezone $date = new DateTime(null); echo 'Default timezone: '.$date->getTimestamp().'<br />'."\r\n";  //America/New_York $date = new DateTime(null, new DateTimeZone('America/New_York')); echo 'America/New_York: '.$date->getTimestamp().'<br />'."\r\n";  //Europe/Amsterdam $date = new DateTime(null, new DateTimeZone('Europe/Amsterdam')); echo 'Europe/Amsterdam: '.$date->getTimestamp().'<br />'."\r\n";  echo 'WORK AROUND<br />'."\r\n"; // WORK AROUND //default timezone $date = new DateTime(null); echo 'Default timezone: '.($date->getTimestamp() + $date->getOffset()).'<br />'."\r\n";  //America/New_York $date = new DateTime(null, new DateTimeZone('America/New_York')); echo 'America/New_York: '.($date->getTimestamp() + $date->getOffset()).'<br />'."\r\n";  //Europe/Amsterdam $date = new DateTime(null, new DateTimeZone('Europe/Amsterdam')); echo 'Europe/Amsterdam: '.($date->getTimestamp() + $date->getOffset()).'<br />'."\r\n"; ?> 

Get the regular timestamp and add the UTC offset

like image 92
Cecil Zorg Avatar answered Nov 16 '22 19:11

Cecil Zorg


https://en.wikipedia.org/wiki/Unix_time

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

The unix timestamp isn't affected by a timezone setting. Setting the timezone only affects the interpretation of the timestamp value.

like image 40
VolkerK Avatar answered Nov 16 '22 18:11

VolkerK