Php date function date_parse_from_format

Source: Internet
Author: User
The general practice is to split the string into a function, and then obtain the required data, such as the number of days, month, and year, and then combine them to use the strtotime function for conversion.

If you encounter a log file date format such as [29/Feb/2012: 23: 59: 31 + 0800], convert it to a timestamp, what would you do?

The general practice is to split the string into a function, and then obtain the required data, such as the number of days, month, and year, and then combine them to use the strtotime function for conversion.

Timestamp. Is there a more concise way? The answer is yes!

The php date function date_parse_from_format () can retrieve what you want from the specified date format.

Date_parse_from_format ($ format, $ date)

$ Format // The format of the date, for example, 29/Feb/2012: 23: 59: 31, is d/M/Y: H: I: s.

$ Date // the original time character, for example, 29/Feb/2012: 23: 59: 31

Example:

$ Arr = date_parse_from_format ("d/M/Y: H: I: s", "29/Feb/2012: 23: 59: 31"); // execute the function

Return format:

Array
(
[Year] = & gt; 2012
[Month] => 2
[Day] => 29
[Hour] => 23
[Minute] => 59
[Second] => 31
[Fraction] =>
[Warning_count] => 0
[Warnings] => Array
(
)

[Error_count] => 0
[Errors] => Array
(
)

[Is_localtime] =>

)


Then we can use strtotime to convert the time to the timestamp!


Note: date_parse_from_format can be used only in php5.3 and later versions. if your version is not high enough, it doesn't matter.

You can use the same method as follows:

If (! Function_exists ('date _ parse_from_format ')){
Function date_parse_from_format ($ format, $ date ){
$ DMask = array (
'H' => 'hour ',
'I' => 'Minute ',
'S '=> 'second ',
'Y' => 'year ',
'M' => 'month ',
'D' => 'day'

);
$ Format = preg_split ('//', $ format,-1, PREG_SPLIT_NO_EMPTY );
$ Date = preg_split ('//', $ date,-1, PREG_SPLIT_NO_EMPTY );
Foreach ($ date as $ k => $ v ){
If ($ dMask [$ format [$ k])
$ Dt [$ dMask [$ format [$ k]. = $ v;
}
Return $ dt;
}
}

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.