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;
}
}