0

I have this date from my local timezone "2019-07-27T02:00:00"

I'm trying to save it to the database in a UTC timezone, so I can deal with it later and convert to to other timezone from UTC,

But when I do:

$date = new \DateTime("2019-07-27T02:00:00");

I got a:

DateTime @1564192800 {#519
  date: 2019-07-27 02:00:00.0 UTC (+00:00)
}

Whatever I set here,

new \DateTime("2019-07-26T06:00:00")

I still get a UTC timezone, so this example

$date = new \DateTime("2019-07-26T06:00:00");

Will get me a result of:

DateTime @1564120800 {#519
  date: 2019-07-26 06:00:00.0 UTC (+00:00)
}

It's like the timezone of the date (2019-07-26T06:00:00) is already in UTC? But it's not (?). So, converting it to UTC with

$date->setTimezone(new \DateTimeZone('UTC')) 

has no affect at all.

6
  • 2
    What does your php.ini file have set for timezone? You can also check with echo date_default_timezone_get() Commented Jul 26, 2019 at 17:57
  • A good way to do, see this post stackoverflow.com/questions/32139407/… T Commented Jul 26, 2019 at 17:59
  • Possible duplicate of Storing datetime as UTC in PHP/MySQL Commented Jul 26, 2019 at 17:59
  • @Das_Geek , UTC :( Commented Jul 26, 2019 at 18:18
  • @Das_Geek, thank you, now I know I have to change it before dealing with the coming date first. if you put your comment somehow as an answer I'll accept it. Thanks a lot. Commented Jul 26, 2019 at 18:21

1 Answer 1

2

PHP probably thinks you're already in UTC, and accepts any DateTime object that doesn't have timezone explicitly listed as UTC as well.

You can check what PHP thinks is your timezone by looking in your php.ini file, or by using the command echodate_default_timezone_get(). Similarly, you can edit your timezone globally by editing your php.ini file or using date_default_timezone_set().

This is a list of timezones PHP can use.

 

As a side note: though it might seem like a good idea to keep your global timezone set to UTC and just use a DateTime/DateTimeZone to set local variables to the correct offset, don't do it. It'll affect the timestamps of your logs, and can lead to some very painful gotchas.

Sign up to request clarification or add additional context in comments.

1 Comment

There are 2 acceptable occasions to have timestamps in anything other than UTC: 1. User input that you are about to convert to UTC. 2. A formatted string that you are about to put in front of human eyeballs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.