-4

I am trying to convert times to and from the following timezones, regardless of when or where the code is run:

  • The timezone of the running code
  • AEST (Australian Eastern Standard Time)
  • EDT (New York Eastern Daylight Time)

For example, given a unix timestamp, how do I find a new unix timestamp "monday the same week" using EDT timezone? How do I do this, such that it will always give the same result?

Hanky Panky
  • 46,730
  • 8
  • 72
  • 95
grasevski
  • 2,894
  • 2
  • 21
  • 22

1 Answers1

47

First you have to understand that a Unix Timestamp has nothing to do with timezones, it is always relative to UTC/GMT. To quote from the manual

Returns the current time measured in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT).

Now that you know one timestamp represents a fixed time in reference to GMT/UTC you can go ahead and change time zones in your code to calculate time for them form the same timestamp.

Let us say you have a unix timestamp

$ts = 1171502725;

If you create a date from it you would do something like

$date = new DateTime("@$ts");
echo $date->format('U = Y-m-d H:i:s T') . "\n";

Now you want to see what does that correspond to in EST, you can do

$date->setTimezone(new DateTimeZone('America/New_York'));
echo $date->format('U = Y-m-d H:i:s T') . "\n";

Similarly for CST

$date->setTimezone(new DateTimeZone('America/Chicago'));
echo $date->format('U = Y-m-d H:i:s T') . "\n";

And so on :)

Output

1171502725 = 2007-02-15 01:25:25 GMT+0000
1171502725 = 2007-02-14 20:25:25 EST
1171502725 = 2007-02-14 19:25:25 CST

Fiddle

You can get a list of supported timezones and their identifiers from the PHP Manual

Hanky Panky
  • 46,730
  • 8
  • 72
  • 95
  • 2
    micro-nitpick: (1) in general, "Unix Timestamp" counts only non-leap SI seconds in [POSIX](http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_15) e.g., 2 seconds elapsed between `2015-06-30 18:59:59 CST` and `2015-06-30 19:00:00 CST` (there is a leap second in between) but the POSIX time counts only 1 second. (2) In non-POSIX case, Unix timestamp may be different e.g., if `"right/UTC"` timezone is used then the timestamp represents actual elapsed SI seconds (TAI time scale, epoch: January 1 1970 00:00:10 TAI). – jfs Nov 10 '15 at 21:41
  • no. first you have to understand that I wanted EDT timezone, all year round. – grasevski Sep 12 '19 at 04:29