在PHP中将字符串转换为日期
问题描述:
如何将字符串05/Feb/2010:14:00:01
转换为unixtime?
How can I convert this string 05/Feb/2010:14:00:01
to unixtime ?
答
对于PHP 5.3,这应该可以工作.您可能需要通过传递$ dateInfo ['is_dst']来摆弄,无论如何对我来说都是无效的.
For PHP 5.3 this should work. You may need to fiddle with passing $dateInfo['is_dst'], wasn't working for me anyhow.
$date = '05/Feb/2010:14:00:01';
$dateInfo = date_parse_from_format('d/M/Y:H:i:s', $date);
$unixTimestamp = mktime(
$dateInfo['hour'], $dateInfo['minute'], $dateInfo['second'],
$dateInfo['month'], $dateInfo['day'], $dateInfo['year'],
$dateInfo['is_dst']
);
之前的版本应该可以使用.
Versions prior, this should work.
$date = '05/Feb/2010:14:00:01';
$format = '@^(?P<day>\d{2})/(?P<month>[A-Z][a-z]{2})/(?P<year>\d{4}):(?P<hour>\d{2}):(?P<minute>\d{2}):(?P<second>\d{2})$@';
preg_match($format, $date, $dateInfo);
$unixTimestamp = mktime(
$dateInfo['hour'], $dateInfo['minute'], $dateInfo['second'],
date('n', strtotime($dateInfo['month'])), $dateInfo['day'], $dateInfo['year'],
date('I')
);
您可能不喜欢正则表达式.您当然可以对其进行注释,但并不是每个人都喜欢.因此,这是另一种选择.
You may not like regular expressions. You could annotate it, of course, but not everyone likes that either. So, this is an alternative.
$day = $date[0].$date[1];
$month = date('n', strtotime($date[3].$date[4].$date[5]));
$year = $date[7].$date[8].$date[9].$date[10];
$hour = $date[12].$date[13];
$minute = $date[15].$date[16];
$second = $date[18].$date[19];
或替换或爆炸,无论您希望解析哪个字符串.
Or substr, or explode, whatever you wish to parse that string.