PHP 5.2 Date, time, and time zone processing detailed

Source: Internet
Author: User
Tags foreach constructor datetime manual time zones time and date time interval valid

Processing date and time need to consider many things, such as the format of the date, time zone, leap year and days of different months, processing too easily error, we should use the PHP 5.2.0 introduced datetime, Dateintervel and Datetimezone These classes help us create and process dates, times, and time zones.

Set the default time zone

First we have to set the default time zone for functions that process dates and times in PHP, and if not, PHP displays a e_warning message, setting the default time zone in two ways, and setting it in PHP.ini as follows:

Date.timezone = ' Asia/shanghai ';

You can also use the Date_default_timezone_set () function setting at run time:

<?php
Date_default_timezone_set (' Asia/shanghai ');

Both of these methods require a valid time zone identifier, and PHP's complete time zone identifier can be found here: http://php.net/manual/zh/timezones.php

DateTime class

The DateTime class provides an object-oriented interface for managing dates and times, and a DateTime instance represents a specific date and time, and the DateTime construction method is the easiest way to create a new DateTime instance:

<?php
$datetime = new DateTime ();

If there are no arguments, the method of constructing the DateTime class creates an instance that represents the current date and time. We can pass a string into the construction method of the DateTime class to specify the date and time:

<?php
$datetime = new DateTime (' 2016-06-06 10:00 pm ');

Note: The passed-in string argument must be a valid date and time format (http://php.net/manual/zh/datetime.formats.php)
Ideally, we would specify a date and time format that PHP can understand, but that's not always the case, and sometimes we have to deal with other formats or unexpected formats, At this point we can create a DateTime instance with a custom format by using the static method Createfromformat DateTime provides, the first parameter of which is a string representing the date and time format, and the second parameter is the date and time string to use this format:

<?php
$datetime = Datetime::createfromformat (' M J, Y h:i:s ', ' June 6, 2016 22:00:00 ');
Note: Maybe you look familiar, yes, Datetime::createfromformat is similar to the date function. Available date-time format references here: http://php.net/manual/zh/datetime.createfromformat.php

DateInterval class

Before processing a DateTime instance, you need to understand the DateInterval class, where the DateInterval instance represents a fixed length of time (for example, two days), or a relative period of time (for example, yesterday), where we usually modify the DateTime instance using an instance of the class. For example, DateTime provides add and sub methods for processing datetime instances, and the arguments for these methods are a DateInterval instance that represents the amount of time or time that has been increased from DateTime.

We instantiate the DateInterval instance using the constructor, and the DateInterval Constructor's argument is a string representing the time interval convention, which begins with the letter p, followed by an integer, and finally a periodic identifier that qualifies the preceding integer. The valid cycle identifier is as follows:

Y (year)
M (month)
D (Day)
W (Zhou)
H (Time)
M (min)
S (sec)

The interval convention can have both time and date, and if there is time to add the letter T between the date and time, for example, the interval agreement p2d represents the interval of two days, the interval convention p2dt5h2m the interval of two days five hours two minutes.

The following example demonstrates how to use the Add method to backward the date and time represented by a DateTime instance for a period of time:

<?php
Create a DateTime instance
$datetime = new DateTime (' 2016-06-06 22:00:00 ');

Create a two-day interval
$interval = new DateInterval (' p2d ');

modifying datetime instances
$datetime->add ($interval);
echo $datetime->format (' y-m-d h:i:s ');

We can also create reverse DateInterval instances:

<?php
$datetime = new DateTime ();
$interval = dateinterval::createfromdatestring ('-1 day ');
$period = new Dateperiod ($datetime, $interval, 3);
foreach ($period as $date) {
echo $date->format (' y-m-d '), Php_eol;
}

The above code output is:

2016-06-06
2016-06-05
2016-06-04
2016-06-03

Datetimezone class

PHP uses the Datetimezone class to represent the time zone, and we only need to pass a valid time zone identifier to the constructor of the Datetimezone class:

<?php
$timezone = new Datetimezone (' Asia/shanghai ');

Creating a DateTime instance usually requires the use of a Datetimezone instance, and the second parameter of the DateTime class constructor (optionally) is a Datetimezone instance, which, after passing in the parameter, The value of the DateTime instance and all modifications to the value are relative to this specified time zone, and if not passed on, the default time zone that was previously set is used:

<?php
$timezone = new Datetimezone (' Asia/shanghai ');
$datetime = new DateTime (' 2016-06-06 ', $timezone);
After instantiating, you can also modify the time zone of a DateTime instance using the Settimezone method:

<?php
$timezone = new Datetimezone (' Asia/shanghai ');
$datetime = new DateTime (' 2016-06-06 ', $timezone);
$datetime->settimezone (New Datetimezone (' Asia/hong_kong '));

Dateperiod class

Sometimes we need to iterate over a series of recurring dates and times over a period of time, and the Dateperiod class can solve this problem (which has been used before), and the construction method of the Dateperiod class accepts three parameters and must provide:

A DateTime instance that represents the date and time the iteration started
An DateInterval instance that represents the interval between the next date and time
An integer that represents the total number of iterations

The Dateperiod is an iterator, and each iteration produces a DateTime instance. The fourth parameter of the dateperiod is optional, used to explicitly specify the end date and time of the cycle, and if the iteration wants to exclude the start date and time, you can set the last parameter of the constructor to the Dateperiod::exclude_start_date constant:

<?php
$datetime = new DateTime ();
$interval = new DateInterval (' p2d ');
$period = new Dateperiod ($datetime, $interval, 3, dateperiod::exclude_start_date);
foreach ($period as $date) {
echo $date->format (' y-m-d h:i:s '), Php_eol;
}

The results of printing are:

2016-06-08
2016-06-10
2016-06-12

Nesbot/carbon Date Component

If you frequently need to process dates and times, you should use the Nesbot/carbon component (Https://github.com/briannesbitt/Carbon), and the Laravel framework also uses this component to process dates and times. The component integrates the commonly used date and time processing APIs, and the bottom layer uses several of the date-time processing classes we mentioned above to implement various functions, which are interesting to study.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.