How to manage timezones in PHP — SitePoint

1674611538php timezone2


This Quick Tips article covers the basics of how to use timezones in PHP. Working with time zones is an essential skill for any programmer working with web applications. PHP has been used primarily for web applications for years, so it has very simple yet comprehensive timezone support.

Timezones and PHP

Timezones are supported in PHP since version 4. date_default_timezone_set() Features evolved rapidly in versions 5 and 7 with the introduction of . DateTimeZone When DateTimeZoneImmutable class.

of DateTimeZoneImmutable is a subclass of DateTimeZone This allows you to create time zones that are immune to changes. This feature is very useful in situations where you need to prevent timezone changes.

of date_default_timezone_set() function sets the default timezone used by all time/date functions in a particular script. This function allows you to set the timezone, but it has very little granularity, so the same timezone should be used throughout script execution.

of DateTimeZone When DateTimeZoneImmutable Classes have brought more control and versatility to working with timezones. Now you have access to all sorts of information about timezones, and the same script can access multiple instances with different timezones.

Using PHP timezones

As mentioned above, there are two main ways to use timezones in PHP.

Using date_default_timezone_set()


time zone of date_default_timezone_set() Methods are always defined in “continent/city” or “continent/country/city” format. See here for the full list of timezones allowed in PHP.

This sets the timezone to the timezone passed as an argument.After setting the timezone you can use a function like date_default_timezone_get() or any other time related function date() Access new time zone information.

Using the DateTimeZone class

A better way to use timezones in PHP is to use DateTimeZone class. This means you have access to more functions to access information and work with timezones, and you can instantiate multiple instances of the class, thus working with multiple timezones.

    $timezone = newDateTimeZone('America/Chicago');
    $datetime = new DateTime($date, $timezone);
    echo $datetime->format('Y-m-d H:i:s');

In this example, the new DateTimeZone create an object and pass it to the new instance DateTime. of DateTime the object is DateTimeZone object.Finally, we format() A function that outputs the date in the desired format.


As you’ve seen, working with timezones in PHP is fairly straightforward. Choose the working method that best fits your use case. PHP does.


Source link

What do you think?

Leave a Reply

GIPHY App Key not set. Please check settings

    128489542 johnsoncommonsparliament

    Kim Johnson: Labour MP apologises for calling Israeli government 'fascist'

    128489435 hi019966478

    Beyoncé announces Renaissance world tour