Search code examples
phpdatetimeunix-timestamp

PHP get unix timestamp from string without setting default timezone


I have a precise date of 1/1/2020 00:00:00 America/Los_Angeles time that I want to convert into a UNIX timestamp. Many answers out there want to set a default timezone using date_default_timezone_set before inserting the string into strtotime() function. But I do not want to mess with the default timezone of the server (which is probably UTC).

Is there anything wrong with doing strtotime("1/1/2020 00:00:00 America/Los_Angeles") to get my timestamp?

I get the correct UNIX value this way. It's just, there's nothing in the docs to indicate this is valid.


Solution

  • As your time str has time zone, there is no need to set the default time zone. But when you want to print it, you need to set default timezone.

    php > echo date_default_timezone_get();
    UTC
    
    php > echo date("Y-m-d H:i:s",strtotime("1/1/2020 00:00:00 America/Los_Angeles"));
    2020-01-01 08:00:00
    
    php > echo date("Y-m-d H:i:s",strtotime("1/1/2020 00:00:00"));
    2020-01-01 00:00:00