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.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Ahmad
  • 13
  • 2
  • 2
    What does your `php.ini` file have set for `timezone`? You can also check with `echo date_default_timezone_get()` – Das_Geek Jul 26 '19 at 17:57
  • A good way to do, see this post https://stackoverflow.com/questions/32139407/php-convert-local-time-to-utc/32139499 T – Joseph Jul 26 '19 at 17:59
  • Possible duplicate of [Storing datetime as UTC in PHP/MySQL](https://stackoverflow.com/questions/1349280/storing-datetime-as-utc-in-php-mysql) – Das_Geek Jul 26 '19 at 17:59
  • @Das_Geek , UTC :( – Ahmad Jul 26 '19 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. – Ahmad Jul 26 '19 at 18:21
  • @Ahmad Posted the answer – Das_Geek Jul 26 '19 at 18:37

1 Answers1

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.

Das_Geek
  • 2,775
  • 7
  • 20
  • 26
  • 1
    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. – Sammitch Jul 26 '19 at 23:44