php strtotime() function returns blank/0
I have datetime data in string format like this:
Sat Mar 24 23:59:59 GMT 2012
I want to convert this into a UTC timestamp, but when I try it as follows:
function texttotime($texttime)
{
if(!$texttime || $texttime=="")
return NULL;
// Sat Mar 24 23:59:59 GMT 2012
$bits = preg_split('/\s/', $texttime);
// Mar 24 2012 23:59:59 GMT
return strtotime("$bits[1] $bits[2] $bits[5] $bits[3] bits[4]");
}
It outputs 0 (not NULL).
If I change the last line to:
// Mar开发者_如何学编程 24 2012 23:59:59
return strtotime("$bits[1] $bits[2] $bits[5] $bits[3]");
It outputs something (but the wrong timestamp, off by -4 hours or so).
Not quite sure why you're re-organising the existing string, as...
echo $timestamp = strtotime('Sat Mar 24 23:59:59 GMT 2012');
...works correctly. (It returns 1332633599, which you can check via date('r', 1332633599);
(This will result in "Sat, 24 Mar 2012 23:59:59 +0000", so all is well.)
That said, if you're going to extract all of the components of the string, you might as well use mktime. For example:
function texttotime($texttime) {
if(!$texttime || $texttime=="") return NULL;
list($junk, $month, $day, $time, $timezone, $year) = explode(' ', $texttime);
list($hour, $minute, $second) = explode(':', $time);
return mktime($hour, $minute, $second, $month, $day, $year);
}
The reason you have 4 hour difference is caused by server timezone which is -4 hours from GMT. try to define your current timezone like this:
date_default_timezone_set('Europe/London');
$result = strtotime('Sat Mar 24 23:59:59 GMT 2012');
echo date('r', $result);//Sat, 24 Mar 2012 23:59:59 +0000
精彩评论