我有一个ISO日期格式字符串,例如MMM d, y h:mm:ss a
。如何将其转换为php date
功能可接受的格式?我希望这样做:M j, y g:i:s A
。
Zend框架有一种将php格式转换为iso的方法:
public static function convertPhpToIsoFormat($format)
{
if ($format === null) {
return null;
}
$convert = array('d' => 'dd' , 'D' => 'EE' , 'j' => 'd' , 'l' => 'EEEE', 'N' => 'eee' , 'S' => 'SS' ,
'w' => 'e' , 'z' => 'D' , 'W' => 'ww' , 'F' => 'MMMM', 'm' => 'MM' , 'M' => 'MMM' ,
'n' => 'M' , 't' => 'ddd' , 'L' => 'l' , 'o' => 'YYYY', 'Y' => 'yyyy', 'y' => 'yy' ,
'a' => 'a' , 'A' => 'a' , 'B' => 'B' , 'g' => 'h' , 'G' => 'H' , 'h' => 'hh' ,
'H' => 'HH' , 'i' => 'mm' , 's' => 'ss' , 'e' => 'zzzz', 'I' => 'I' , 'O' => 'Z' ,
'P' => 'ZZZZ', 'T' => 'z' , 'Z' => 'X' , 'c' => 'yyyy-MM-ddTHH:mm:ssZZZZ',
'r' => 'r' , 'U' => 'U');
$values = str_split($format);
foreach ($values as $key => $value) {
if (isset($convert[$value]) === true) {
$values[$key] = $convert[$value];
}
}
return implode($values);
}
我想将此方法的输出转换回php日期格式。
答案 0 :(得分:1)
尝试此操作,使用preg_match()
将您的字符串拆分为令牌和分隔符,转换您的令牌(如果它存在于$convert
数组中,然后将其与您的分隔符一起粘贴到$result
public static function convertIsoToPhpFormat($format) {
if ($format === null) {
return null;
}
$convert = array('dd' => 'd' , 'EE' => 'D' , 'd' => 'j' , 'EEEE' => 'l', 'eee' => 'N' , 'SS' => 'S' ,
'e' => 'w' , 'D' => 'z' , 'ww' => 'W' , 'MMMM' => 'F', 'MM' => 'm' , 'MMM' => 'M' ,
'M' => 'n' , 'ddd' => 't' , 'l' => 'L' , 'YYYY' => 'o' , 'yyyy' => 'Y' , 'yy' => 'y' ,
'a' => 'a' , 'A' => 'A' , 'B' => 'B' , 'h' => 'g' , 'H' => 'G' , 'hh' => 'h' ,
'HH' => 'H' , 'mm' => 'i' , 'ss' => 's' , 'zzzz' => 'e', 'I' => 'I' , 'Z' => 'O' ,
'ZZZZ' => 'P', 'z' => 'T' , 'X' => 'Z' , 'ssZZZZ' => 'se' ,
'r' => 'r' , 'U' => 'U');
// todo: add exceptions like yyyy-MM-ddTHH:mm:ssZZZZ
$result = '';
while (preg_match('/^([^- :,]+)([- :,]*)(.*)$/',$format,$arr_preg)) {
if (isset($convert[$arr_preg[1]]) === true) {
$result .= $convert[$arr_preg[1]];
} else {
$result .= $arr_preg[1];
}
$result .= $arr_preg[2];
$format = $arr_preg[3];
}
return $result;
}