Php format date with timezone

Dates and time zones in PHP

Working on an existing codebase means you can get unexpected surprises, like having dates being represented as strings inside application logic. We decided to migrate this to PHP’s DateTime objects. While migrating some of these string to DateTime instances in our codebase I came across code where we create a DateTime object based on data from our database and from API responses. The time zones of our application and our website are one and the same, but some APIs tend to send their data in UTC. And our default time zone is Europe/Amsterdam. What can possibly go wrong?!

Naive

The code I found used a naive solution. Although it might look good — we add a time zone, right? — the result is not what I expected:

// somewhere in our application bootstrap date_default_timezone_set('Europe/Amsterdam'); // somewhere deep in our application $date = \DateTimeImmutable::createFromFormat( \DateTime::ATOM, '2020-07-23T12:00:00+00:00' ); // let's output print $date->format('c'); 

This will print 2020-07-23T12:00:00+00:00 . Nice! Now let’s show this to our users. Users typically don’t care for time zones, they just want to know what the date and time is for them. You might want to localize this, but for now I will use the format YYYY-MM-DD HH:MM:SS . So what will be the output of $date using this format when in Europe/Amsterdam? 2020-07-23 12:00:00 . Hmmmz, that’s not right. I expected this to be 2020-07-23 14:00:00 , seeing that Amsterdam is in UTC + 2:00. NB I’m using DateTimeImmutable in my examples and not DateTime . This is deliberate. As DateTime objects are mutable by default you can find yourself in unexpected situations. An example is when you pass a DateTime object to a different class or function. You don’t know what this class or function will do with that object and if it decides to use add or sub your instance will be affected:

function getUpcomingOpeningHours(DateTime $start): array  $database->query( '/* query */', [ 'start' => $start, 'end' => $start->add(new DateInterval('P7D')) ] ); > $date = new DateTime(); $openingHours = getUpcomingOpeningHours($date); print "Upcoming opening hours since $format('Y-m-d')>: "; 

Specify a time zone 1

A look at the documentation of DateTime::createFromFormat shows it accepts a third parameter; an instance of DateTimeZone :

// set the default time zone date_default_timezone_set('Europe/Amsterdam'); // create a date object $date = \DateTimeImmutable::createFromFormat( \DateTime::ATOM, '2020-07-23T12:00:00+00:00', new \DateTimeZone(date_default_timezone_get()) ); // show the user print $date->format('Y-m-d H:i:s'); 

The timezone parameter and the current timezone are ignored when the time parameter either contains a UNIX timestamp (e.g. 946684800) or specifies a timezone (e.g. 2010-01-28T15:00:00+02:00).

This means that this approach only works if the date time string you are receiving is set in a specific time zone, but does not have a time zone indication in the date time string. In my personal opinion that is an undesirable situation, but I have seen far worse:

// set the default time zone date_default_timezone_set('Europe/Amsterdam'); // create a date object $date = \DateTimeImmutable::createFromFormat( 'Y-m-d H:i:s', '2020-07-23 12:00:00', new \DateTimeZone(date_default_timezone_get()) ); // show the user print $date->format('Y-m-d H:i:s'); 

This prints 2020-07-23 12:00:00 ; winning! But wait, this example does not make any sense. If you create a DateTime object without any time zone specification it will use the default time zone. What happens if we specify a different time zone?

// set the default time zone date_default_timezone_set('Europe/Amsterdam'); // create a date object $date = \DateTimeImmutable::createFromFormat( 'Y-m-d H:i:s', '2020-07-23 12:00:00', new \DateTimeZone('UTC') ); // show the user print $date->format('Y-m-d H:i:s'); 

Specify a time zone 2

// set the default time zone date_default_timezone_set('Europe/Amsterdam'); // create a date object $date = \DateTimeImmutable::createFromFormat( \DateTime::ATOM, '2020-07-23T12:00:00+00:00' )->setTimeZone(new \DateTimeZone(date_default_timezone_get())); // show the user print $date->format('Y-m-d H:i:s'); 

This will print 2020-07-23 14:00:00 . Which is correct since at July 23rd 2020 Europe/Amsterdam is +02:00 . I’m using the functions date_default_timezone_set() and date_default_timezone_get() . Unless you let your users specify their time zone themselves I would recommend using these functions — or abstractions of them — in your code for this. By consistently using date_default_timezone_get() you make sure your code will not break once it gets decided your application should also become available in territories with a different time zone. You need to make sure that somewhere in the bootstrap of your application you specify the correct time zone, and your entire application should follow you in the time zone migration.

tl;dr

When you’re building DateTime objects from date time strings and you want to use it to display a human readable date time format always specify the time zone of the object by using DateTime::setTimezone() . And to ensure you don’t end up showing incorrect times it is always a good idea to either store or submit a timestamp, which is by definition in UTC — but can only represent dates after the unix epoch, or a date time with a time zone indication.

Источник

date_timezone_set

The procedural version takes the DateTime object as its first argument.

Parameters

Procedural style only: A DateTime object returned by date_create() . The function modifies this object.

A DateTimeZone object representing the desired time zone.

Return Values

Returns the DateTime object for method chaining. The underlaying point-in-time is not changed when calling this method.

Examples

Example #1 DateTime::setTimeZone() example

$date = new DateTime ( ‘2000-01-01’ , new DateTimeZone ( ‘Pacific/Nauru’ ));
echo $date -> format ( ‘Y-m-d H:i:sP’ ) . «\n» ;

$date -> setTimezone (new DateTimeZone ( ‘Pacific/Chatham’ ));
echo $date -> format ( ‘Y-m-d H:i:sP’ ) . «\n» ;
?>

$date = date_create ( ‘2000-01-01’ , timezone_open ( ‘Pacific/Nauru’ ));
echo date_format ( $date , ‘Y-m-d H:i:sP’ ) . «\n» ;

date_timezone_set ( $date , timezone_open ( ‘Pacific/Chatham’ ));
echo date_format ( $date , ‘Y-m-d H:i:sP’ ) . «\n» ;
?>

The above examples will output:

2000-01-01 00:00:00+12:00 2000-01-01 01:45:00+13:45

See Also

  • DateTimeImmutable::setTimezone() — Sets the time zone
  • DateTime::getTimezone() — Return time zone relative to given DateTime
  • DateTimeZone::__construct() — Creates new DateTimeZone object

User Contributed Notes

Источник

date_format

The format of the outputted date string . See the formatting options below. There are also several predefined date constants that may be used instead, so for example DATE_RSS contains the format string ‘D, d M Y H:i:s’ .

The following characters are recognized in the format parameter string

format character Description Example returned values
Day
d Day of the month, 2 digits with leading zeros 01 to 31
D A textual representation of a day, three letters Mon through Sun
j Day of the month without leading zeros 1 to 31
l (lowercase ‘L’) A full textual representation of the day of the week Sunday through Saturday
N ISO 8601 numeric representation of the day of the week 1 (for Monday) through 7 (for Sunday)
S English ordinal suffix for the day of the month, 2 characters st , nd , rd or th . Works well with j
w Numeric representation of the day of the week 0 (for Sunday) through 6 (for Saturday)
z The day of the year (starting from 0) 0 through 365
Week
W ISO 8601 week number of year, weeks starting on Monday Example: 42 (the 42nd week in the year)
Month
F A full textual representation of a month, such as January or March January through December
m Numeric representation of a month, with leading zeros 01 through 12
M A short textual representation of a month, three letters Jan through Dec
n Numeric representation of a month, without leading zeros 1 through 12
t Number of days in the given month 28 through 31
Year
L Whether it’s a leap year 1 if it is a leap year, 0 otherwise.
o ISO 8601 week-numbering year. This has the same value as Y , except that if the ISO week number ( W ) belongs to the previous or next year, that year is used instead. Examples: 1999 or 2003
X An expanded full numeric representation of a year, at least 4 digits, with — for years BCE, and + for years CE. Examples: -0055 , +0787 , +1999 , +10191
x An expanded full numeric representation if requried, or a standard full numeral representation if possible (like Y ). At least four digits. Years BCE are prefixed with a — . Years beyond (and including) 10000 are prefixed by a + . Examples: -0055 , 0787 , 1999 , +10191
Y A full numeric representation of a year, at least 4 digits, with — for years BCE. Examples: -0055 , 0787 , 1999 , 2003 , 10191
y A two digit representation of a year Examples: 99 or 03
Time
a Lowercase Ante meridiem and Post meridiem am or pm
A Uppercase Ante meridiem and Post meridiem AM or PM
B Swatch Internet time 000 through 999
g 12-hour format of an hour without leading zeros 1 through 12
G 24-hour format of an hour without leading zeros 0 through 23
h 12-hour format of an hour with leading zeros 01 through 12
H 24-hour format of an hour with leading zeros 00 through 23
i Minutes with leading zeros 00 to 59
s Seconds with leading zeros 00 through 59
u Microseconds. Note that date() will always generate 000000 since it takes an int parameter, whereas DateTime::format() does support microseconds if DateTime was created with microseconds. Example: 654321
v Milliseconds. Same note applies as for u . Example: 654
Timezone
e Timezone identifier Examples: UTC , GMT , Atlantic/Azores
I (capital i) Whether or not the date is in daylight saving time 1 if Daylight Saving Time, 0 otherwise.
O Difference to Greenwich time (GMT) without colon between hours and minutes Example: +0200
P Difference to Greenwich time (GMT) with colon between hours and minutes Example: +02:00
p The same as P , but returns Z instead of +00:00 (available as of PHP 8.0.0) Examples: Z or +02:00
T Timezone abbreviation, if known; otherwise the GMT offset. Examples: EST , MDT , +05
Z Timezone offset in seconds. The offset for timezones west of UTC is always negative, and for those east of UTC is always positive. -43200 through 50400
Full Date/Time
c ISO 8601 date 2004-02-12T15:19:21+00:00
r » RFC 2822/» RFC 5322 formatted date Example: Thu, 21 Dec 2000 16:01:07 +0200
U Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT) See also time()

Unrecognized characters in the format string will be printed as-is. The Z format will always return 0 when using gmdate() .

Note:

Since this function only accepts int timestamps the u format character is only useful when using the date_format() function with user based timestamps created with date_create() .

Return Values

Returns the formatted date string on success.

Источник

Читайте также:  Java objects to xml string
Оцените статью