PHP - strtotime, specify timezone

PhpDateTimezone

Php Problem Overview


I have a date string, say '2008-09-11'. I want to get a timestamp out of this, but I need to specify a timezone dynamically (rather then PHP default).

So to recap, I have two strings:

$dateStr = '2008-09-11';
$timezone = 'Americas/New_York';

How do I get the timestamp for this?

EDIT: The time of day will be the midnight of that day.... $dateStr = '2008-09-11 00:00:00';

Php Solutions


Solution 1 - Php

$date = new DateTime($dateStr, new DateTimeZone($timezone));

$timestamp = $date->format('U');

Solution 2 - Php

The accepted answer is great if you're running PHP > 5.2 (I think that's the version they added the DateTime class). If you want to support an older version, you don't want to type as much, or if you just prefer the functional approach there is another way which also does not modify global settings:

$dateStr = '2008-09-11 00:00:00';
$timezone = 'America/New_York';
$dtUtcDate = strtotime($dateStr. ' '. $timezone);

Solution 3 - Php

This will work if for some reason you're using <5.2 (Heaven forbid).

$reset = date_default_timezone_get();
date_default_timezone_set('America/New_York');
$stamp = strtotime($dateStr);
date_default_timezone_set($reset);

But anything 5.2 and above, I'd strongly recommend you opt for @salathe's answer.

Solution 4 - Php

If you're going to use Timezones, I propose you use the DateTime class, and in this case the DateTime::createFromFormat() function which will allow you to do something like this:

$start = "2015-01-14 11:59:43";
$timezone = "America/Montreal";
 
$tz = new DateTimeZone($timezone);
$dt = DateTime::createFromFormat('Y-m-d H:i:s', $start, $tz);

When you put $tz in the DateTime::createFromFormat function, you tell it what time zone the date you gave is in, so that when you need to convert it to another timezone, all you have to do is something like this:

$start = $dt->setTimeZone(new DateTimeZone('UTC'));

Solution 5 - Php

Whenever you are referring to an exact moment in time, persist the time according to a unified standard that is not affected by daylight savings. (GMT and UTC are equivalent with this regard, but it is preferred to use the term UTC. Notice that UTC is also known as Zulu or Z time.)

If instead you choose to persist a time using a local time value, include the local time offset from UTC, such that the timestamp can later be interpreted unambiguously.

In some cases, you may need to store both the UTC time and the equivalent local time. Often this is done with two separate fields, but some platforms support a datetimeoffset type that can store both in a single field.

When storing timestamps as a numeric value, use Unix time - which is the number of whole seconds since 1970-01-01T00:00:00Z (excluding leap seconds). If you require higher precision, use milliseconds instead. This value should always be based on UTC, without any time zone adjustment.

If you might later need to modify the timestamp, include the original time zone ID so you can determine if the offset may have changed from the original value recorded.

When scheduling future events, usually local time is preferred instead of UTC, as it is common for the offset to change. See answer, and blog post.

Remember that time zone offsets are not always an integer number of hours (for example, Indian Standard Time is UTC+05:30, and Nepal uses UTC+05:45).

If using Java, use java.time for Java 8, or use Joda Time for Java 7 or lower. If using .NET, consider using Noda Time. If using .NET without Noda Time, consider that DateTimeOffset is often a better choice than DateTime. If using Perl, use DateTime. If using Python, use pytz or dateutil. If using JavaScript, use moment.js with the moment-timezone extension. If using PHP > 5.2, use the native time zones conversions provided by DateTime, and DateTimeZone classes. Be careful when using.

DateTimeZone::listAbbreviations() - see answer. To keep PHP with up to date Olson data, install periodically the timezonedb PECL package; see answer.

If using C++, be sure to use a library that uses the properly implements the IANA timezone database. These include cctz, ICU, and Howard Hinnant's "tz" library.

Do not use Boost for time zone conversions. While its API claims to support standard IANA (aka "zoneinfo") identifiers, it crudely maps them to fixed offsets without considering the rich history of changes each zone may have had.

(Also, the file has fallen out of maintenance.)

Most business rules use civil time, rather than UTC or GMT. Therefore, plan to convert UTC timestamps to a local time zone before applying application logic.

Remember that time zones and offsets are not fixed and may change. For instance, historically US and UK used the same dates to 'spring forward' and 'fall back'.

However, in 2007 the US changed the dates that the clocks get changed on. This now means that for 48 weeks of the year the difference between London time and New York time is 5 hours and for 4 weeks (3 in the spring, 1 in the autumn) it is 4 hours. Be aware of items like this in any calculations that involve multiple zones.

Consider the type of time (actual event time, broadcast time, relative time, historical time, recurring time) what elements (timestamp, time zone offset and time zone name) you need to store for correct retrieval - see "Types of Time" in answer.

Keep your OS, database and application tzdata files in sync, between themselves and the rest of the world.

On servers, set hardware clocks and OS clocks to UTC rather than a local time zone.

Regardless of the previous bullet point, server-side code, including web sites, should never expect the local time zone of the server to be anything in particular. see answer.

Use NTP services on all servers.

If using FAT32, remember that timestamps are stored in local time, not UTC.

When dealing with recurring events (weekly TV show, for example), remember that the time changes with DST and will be different across time zones.

Always query date-time values as lower-bound inclusive, upper-bound exclusive (>=, <).

Solution 6 - Php

Laconic Answer (no need to change default timezone)

$dateStr = '2008-09-11';
$timezone = 'America/New_York';
$time = strtotime(
    $dateStr, 
    // convert timezone to offset seconds
    (new \DateTimeZone($timezone))->getOffset(new \DateTime) - (new \DateTimeZone(date_default_timezone_get()))->getOffset(new \DateTime) . ' seconds'
);

Loquacious Answer

Use strtotime's second option which changes the frame of reference of the function. By the way I prefer not to update the default time zone of the script:

> http://php.net/manual/en/function.strtotime.php

> int strtotime ( string $time [, int $now = time() ] )

> The function > expects to be given a string containing an English date format and > will try to parse that format into a Unix timestamp (the number of > seconds since January 1 1970 00:00:00 UTC), relative to the timestamp > given in now, or the current time if now is not supplied.

And a Helper

/**
 * Returns the timestamp of the provided time string using a specific timezone as the reference
 * 
 * @param string $str
 * @param string $timezone
 * @return int number of the seconds
 */
function strtotimetz($str, $timezone)
{
    return strtotime(
        $str, strtotime(
            // convert timezone to offset seconds
            (new \DateTimeZone($timezone))->getOffset(new \DateTime) - (new \DateTimeZone(date_default_timezone_get()))->getOffset(new \DateTime) . ' seconds'
        )
    );
}

var_export(
    date(
        'Y-m-d', 
        strtotimetz('this monday', 'America/New_York')
    )
);

Maybe not the most performant approach, but works well when you know the default timezone and the offset. For example if the default timezone is UTC and the offset is -8 hours:

var_dump(
    date(
        'Y-m-d', 
        strtotime('this tuesday', strtotime(-8 . ' hours'))
    )
);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAndy HinView Question on Stackoverflow
Solution 1 - PhpsalatheView Answer on Stackoverflow
Solution 2 - PhpkroweView Answer on Stackoverflow
Solution 3 - PhpJonahView Answer on Stackoverflow
Solution 4 - PhpPhilippe GilbertView Answer on Stackoverflow
Solution 5 - PhpCharuView Answer on Stackoverflow
Solution 6 - PhphpakniaView Answer on Stackoverflow