7

I send UNIX timestamp from javascript vat stamp = +new Date/1000 to PHP.

Then I do

//Here $d = '2015/04/03 00:00:00'
$d = new DateTime("@{$stamp}");
$d->setTimezone( new DateTimeZone( 'Pacific/Auckland' ) );

//Here $d = '2015/04/03 00:00:00' + 7:15 hrs ( 7:15 hrs is time diff between my browser & Auckland)

I want to change the timezone but keep the date to same. So, after I setTimezone to Pacific/Auckland, the date should still be '2015/04/03 00:00:00'.

1
  • Take the timestamp coming into php and store it as a variable, and the convert the present date in the different timezone and compare the two and adjust + or - from there
    – MrTechie
    Apr 2, 2015 at 6:01

2 Answers 2

33

Here's one way to do it.

$_date = new \DateTime($date->format('Y-m-d H:i:s'), new \DateTimeZone('<time zone>'));
-5

I need to point out that you're asking for something nonsensical. A UNIX timestamp represents an absolute point in time. It does not represent "2015/04/03 00:00:00", because that date format can refer to a few dozen different points in time, depending on which timezone you're interpreting this string in. A UNIX timestamp doesn't have this problem, what point in time it represents is not negotiable based on timezones.

If you take an absolute point in time and want to format it as a human readable time which depends on timezones, then this human readable value will necessarily change by applying a different timezone to it. What you're asking for is to change the point in time the timestamp refers to, at which point it's just arbitrary.

4
  • 2
    To give context to op's question, since I have same need. In my case, I have a database where time is stored with Europe/Paris timezone but is considered as UTC time upon retrieval... So I needed to set timezone without changing time in this special case until I get to fix all dates in database. For now @Henry's answer worked well.
    – Herz3h
    Aug 13, 2020 at 13:57
  • @Herz3h How exactly do you store a UNIX timestamp as "Europe/Paris"?!
    – deceze
    Aug 13, 2020 at 13:59
  • 2
    Wrong wording I guess, what I mean is that the DateTime object that will be used to store the date in db has wrong timezone in first place, and it gets stored in database just as if it has utc timezone.
    – Herz3h
    Aug 13, 2020 at 14:25
  • "has wrong timezone in first place" — Aha, that makes more sense and is really a different problem…
    – deceze
    Aug 13, 2020 at 14:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.