PHP Dates and Times Calculating Time with Time Zones and Daylight Saving Time - Web Development and Design | Tutorial for Java, PHP, HTML, Javascript PHP Dates and Times Calculating Time with Time Zones and Daylight Saving Time - Web Development and Design | Tutorial for Java, PHP, HTML, Javascript

Breaking

Post Top Ad

Post Top Ad

Monday, May 13, 2019

PHP Dates and Times Calculating Time with Time Zones and Daylight Saving Time

PHP Dates and Times






Calculating Time with Time Zones and Daylight Saving Time

Problem

You need to calculate times in different time zones. For example, you want to give users information adjusted to their local time, not the local time of your server.

Solution

Use appropriate DateTimeZone objects when you build DateTime objects and PHP will do all the work for you, as in example.

Example   Simple time zone usage

            $nowInNewYork = new DateTime('now', new DateTimeZone('America/New_York'));
            $nowInCalifornia = new DateTime('now', new DateTimeZone('America/Los_Angeles'));

            printf("It's %s in New York but %s in California.",
                       $nowInNewYork->format(DateTime::RFC850),
                       $nowInCalifornia->format(DateTime::RFC850));

This prints:

            It's Friday, 15-Feb-13 14:50:25 EST in New York but
            Friday, 15-Feb-13 11:50:25 PST in California.

Note how not only is the time localized (the hours shown differ by three) but the time zone displayed is the locally appropriate one as well. If a time zone you’re using observes daylight saving time, this is accounted for automatically.

PHP’s default time zone is set at request startup by the date.timezone configuration parameter. Change this by calling date_default_time_zone_set(); that time zone becomes the new default until changed again or the end of the request. 


Example   Changing time zone with date_default_timezone_set()

            $now = time();
            date_default_timezone_set('America/New_York');
            print date(DATE_RFC850, $now);
            print "\n";

            date_default_timezone_set('Europe/Paris');
            print date(DATE_RFC850, $now);

Discussion

Because DateTime objects cooperate with DateTimeZone objects (and other functions, such as date(), respect the system-set time zone) it is very easy to twiddle time zones and get appropriately formatted output. The time zone information that PHP relies on incorporates daylight saving time transitions as well.

The time zones that PHP understands are listed in the PHP Manual. The names of these time zones—such as America/New_York, Europe/Paris, and Africa/Dar_es_Salaam—mirror the structure of the popular zoneinfo database. If you want to update your time zone database without updating your entire PHP installation, install (or update) the timezonedb extension from PECL. This packages the IANA-managed Time Zone Database for PHP.



No comments:

Post a Comment

Post Top Ad