转换为新日期格式时输出错误



我有一个字符串值"27/03/2015",我想将此字符串转换为新的日期格式。下面是我现在使用的代码。

<?php echo date("Y-m-d",strtotime("27/03/2015")); ?>

但它给出了一个错误的输出,比如1970-01-01。

这是因为strtotime无法解析日期字符串。尝试:

<?php echo strtotime("27/03/2015"); ?>

结果应该是False。由于False0相同,因此您实际上正在运行date("Y-m-d", 0),其结果是"1970-01-01"("unix epoch")。

strtotime仅识别此处列出的某些日期格式。最接近您的输入格式是"27-03-2015"("天、月和四位数的年份,带点、制表符或短划线")。

尝试这个

<?php echo date("Y-m-d",strtotime(str_replace('/', '-',  YOUR DATE )))); ?>

以下是的简单解决方案

$date = '27/03/2015';
$date = str_replace('/', '-', $date);
echo date('Y-m-d', strtotime($date));

在上述情况下/分隔符无效(因为日期将评估为日期3和27)你可以使用-

echo date("Y-m-d",strtotime("27-03-2015"));

我想"/"是不允许的,或者应该说,不可识别为strtotime的参数。

<?php 
$dateString = "27/03/2015";
//now let's check if the variable has a "/" inside of it. 
//If it does, then replace "/" with "-". 
//If it doesnt, then go with it. 
//"." also accepted for strtotime as well.
$dateString = (strpos($dateString,"/") ? str_replace("/","-",$dateString) : $dateString);
echo date("Y-m-d",strtotime($dateString)); 
?>

最新更新