【发布时间】:2014-03-17 10:14:57
【问题描述】:
我正在尝试将 javascript 日期格式(例如“dd/mm/yy”)转换为 PHP 等效格式(例如“d/m/Y”)。这适用于 jQuery datepicker UI。
我找到了一个函数(未经测试)可以反过来做,here。
我把它改了一下,看起来像这样:
function dateFormat(){
$pattern = array(
//day
'dd',
'd',
'DD',
'o',
//month
'MM',
'M',
'mm',
'm',
//year
'yy',
'y'
);
foreach($pattern as &$p)
{
$p = '/'.$p.'/';
}
$replace = array(
//day
'd', //day of the month
'j', //3 letter name of the day
'l', //full name of the day
'z', //day of the year
//month
'F', //Month name full
'M', //Month name short
'm', //numeric month leading zeros
'n', //numeric month no leading zeros
//year
'Y', //full numeric year
'y' //numeric year: 2 digit
);
return preg_replace($pattern, $replace, 'dd/mm/yy');
}
但是,我得到的不是预期的“d/m/Y”,而是“j/n/Y”。我认为它会按顺序进行替换;即在 d 之前找到 dd 并首先替换它。怎么回事?
谢谢。
【问题讨论】:
-
请注意,我已硬编码“dd/mm/yy”用于测试目的。
-
最好的方法可能是使用 DateTime::createFromFormat。
-
JavaScript 没有日期格式代码...
-
对不起,它是在 jQuery 的 datepicker ui 中使用的。我会将其添加到最初的问题中。
-
@CasimiretHippolyte 谢谢,但我正在尝试转换格式字符串,而不是实际日期。
标签: javascript php regex date