该代码输出错误日期的问题是什么?
$date = "1990-05-07"; // Y-m-d
$date1 = date("d/m/Y", strtotime($date)); // Here is fine.
$date2 = date("Y-m-d", strtotime($date1)); // Here is wrong.
echo $date2; // output: 1990-07-05
上面的代码是一个简单的演示,确切的代码是:(Yii Framework)
Model.php
public function afterFind()
{
if ($this->birthday)
{
$this->birthday = date("d/m/Y", strtotime($this->birthday));
}
}
public function beforeSave()
{
if ($this->birthday)
{
$this->birthday = date("Y-m-d", strtotime($this->birthday));
}
}
答案 0 :(得分:2)
因为您正在将$date
从“1990-05-07”更改为“07/05/1990”。您已将其从Y-m-d
更改为d/m/Y
,解析器将其识别为m/d/Y
。你不能重复使用第一个日期调用的resule,因为它不会按你想象的那样解析。
重复使用您从原始日期解析的时间戳,并且不会弄乱原始时间戳:
$date = "1990-05-07"; // Y-m-d
$timestamp = strtotime($date);
$date1 = date("d/m/Y", $timestamp);
$date2 = date("Y-m-d", $timestamp);
echo $date1 . " ; " . $date2;
按@PragneshChauhan说,因为他打我编辑我的帖子。
在$date
的调用之间重置date()
,并且工作正常:
$date = "1990-05-07"; // Y-m-d
$date = date("d/m/Y", strtotime($date));
echo $date; // output: 07/05/1990
echo "\n";
$date = "1990-05-07"; // Y-m-d
$date = date("Y-m-d", strtotime($date));
echo $date; // output: 1990-05-07
答案 1 :(得分:1)
你也可以这样使用它:
<?php
$date = "1990-05-07"; // Y-m-d
$date_ex=explode("-",$date);
$date1=mktime(0,0,0,$date_ex[1],$date_ex[2],$date_ex[0]);
$date=date("d/m/Y",$date1);
$date=date("Y-m-d",$date1);
//echo $date = date("d/m/Y", strtotime($date)); // Here is fine.
//echo $date = date("Y-m-d", strtotime($date)); // Here is wrong.
echo $date; // output: 1990-07-05
?>
答案 2 :(得分:0)
试
$date = "1990-05-07"; // Y-m-d
$date1 = date("d/m/Y", strtotime($date));
$date2 = date("Y-m-d", strtotime($date));
echo $date2; // output: 1990-07-05
答案 3 :(得分:0)
解决方案使用'Vikas Umrao'提示:
public function afterFind()
{
if ($this->birthday)
{
$birthday = explode("-", $this->birthday);
$mktime = mktime(0,0,0,$birthday[1],$birthday[2],$birthday[0]);
$this->birthday = date("d/m/Y",$mktime);
}
}
public function beforeSave()
{
if ($this->birthday)
{
$birthday = explode("/", $this->birthday);
$mktime = mktime(0,0,0,$birthday[1],$birthday[0],$birthday[2]);
$this->birthday = date("Y-m-d",$mktime);
}
}