[Best Practices Series] PHP date, time, and time zone processing APIs and components

Source: Internet
Author: User
[Best Practices Series] PHP date, time and time zone Processing API and component processing date and time need to consider a lot of things, such as the date format, time zone, leap year and days of different months, self-processing is too error-prone. we should use the DateTime, DateIntervel, and DateTimeZone classes introduced by PHP 5.2.0 to help us create and process the date, time, and time zone.

Set default time zone

First, we need to set the default time zone for the function processing date and time in PHP. If this parameter is not set, PHP will display an E_WARNING message. There are two ways to set the default time zone, in php. set in ini:

date.timezone = 'Asia/Shanghai';

You can also use the date_default_timezone_set () function at runtime to set:

     

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

DateTime type

The DateTime class provides an object-oriented interface for date and time management. a DateTime instance represents a specific date and time. The DateTime constructor is the easiest way to create a new DateTime instance:

      

If no parameter exists, the DateTime class constructor 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:

       

Note: Incoming string parameters must be in valid date and time format (http://php.net/manual/zh/datetime.formats.php)

Ideally, we will specify the date and time formats that PHP can understand, but this is not always the case. sometimes we have to deal with other formats or unexpected formats, at this time, we can use the static method createFromFormat provided by DateTime to create a DateTime instance in a custom format. The first parameter of this method is a string representing the date and time formats, the second parameter is a date and time string in this format:

        

Note: You may be familiar with it. that's right. The DateTime: createFromFormat and date functions are similar. Available date and time formats see here: http://php.net/manual/zh/datetime.createfromformat.php

DateInterval class

Before processing DateTime instances, you must first understand the DateInterval class. the DateInterval instance represents a fixed time period (such as two days) or a relatively short time period (such as yesterday ), we usually use instances of this class to modify DateTime instances. For example, DateTime provides the add and sub methods used to process DateTime instances. the parameters of these two methods are a DateInterval instance, indicating the time increase or decrease from DateTime.

We use the constructor to instantiate the DateInterval instance. the parameter of the DateInterval constructor is a string that represents the time interval convention. this time interval convention starts with the letter P, followed by an integer, the last is a periodic identifier that limits the previous integer. The valid period identifier is as follows:

  • Y (year)
  • M (month)
  • D (day)
  • W (week)
  • H (hour)
  • M (points)
  • S (seconds)

There can be both time and date in the interval convention. if there is time, you need to add a letter T between the date and time. for example, the interval convention P2D indicates that the interval is two days, p2DT5H2M indicates that the interval is two days, five hours, and two minutes.

The following example demonstrates how to use the add method to extend the date and time represented by the DateTime instance over a period of time:

     Add ($ interval); echo $ datetime-> format ('Y-m-d H: I: s ');

We can also create a reverse DateInterval instance:

     format('Y-m-d'), PHP_EOL;}

The above code is output:

2016-06-062016-06-052016-06-042016-06-03
DateTimeZone class

PHP uses the DateTimeZone class to represent the time zone. we only need to pass the valid time zone identifier to the constructors of the DateTimeZone class:

         

To create a DateTime instance, you usually need to use a DateTimeZone instance. The second parameter (optional) of the DateTime constructor is a DateTimeZone instance. after this parameter is passed in, the value of the DateTime instance and all modifications to this value are relative to the specified time zone. If this parameter is not set, the default time zone is used:

          

After instantiation, you can also use the setTimezone method to modify the time zone of the DateTime instance:

       setTimezone(new DateTimeZone('Asia/Hong_kong'));
DatePeriod class

Sometimes we need to iterate over a series of dates and times that occur repeatedly over a period of time. the DatePeriod class can solve this problem (previously used ), the constructor of the DatePeriod class accepts three parameters and must provide:

  • A DateTime instance, indicating the date and time at which the iteration starts
  • A DateInterval instance, indicating the interval between the next date and time
  • An integer representing the total number of iterations

DatePeriod is an iterator that generates a DateTime instance for each iteration. The fourth parameter of DatePeriod is optional and is used to explicitly specify the end date and time of the cycle. if you want to exclude the start date and time during iteration, you can set the last parameter of the constructor to the constant DatePeriod: EXCLUDE_START_DATE:

       format('Y-m-d H:i:s'), PHP_EOL;}

The printed result is:

2016-06-082016-06-102016-06-12
Nesbot/carbon date component

If you often need to process date and time, you should use the nesbot/carbon component (https://github.com/briannesbitt/Carbon), Laravel framework also uses this component to process date and time, this component integrates common date and time processing APIs, and its underlying layer uses several date and time processing classes we mentioned above to implement various functions. if you are interested, you can study them.

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.