0

该代码中输出错误日期的问题是什么?

$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)

模型.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));
    }
}
4

4 回答 4

2

因为您正在$date从“1990-05-07”更改为“07/05/1990”。您已将其从 更改Y-m-dd/m/Y,并且解析器将其识别为m/d/Y. 您不能重用第一次约会调用的结果,因为它不会按照您认为的方式解析。

解决方案 1(最佳)

重用你从原始日期解析的时间戳,不会弄乱原始时间戳:

$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;

解决方案2(也不错)

按照@PragneshChauhan所说的去做,因为他打败了我来编辑我的帖子。

解决方案 3(不太理想)

$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

概念证明:http ://codepad.org/JnVpDFb7

于 2012-11-07T06:23:33.780 回答
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
  ?>
于 2012-11-07T06:33:01.260 回答
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
于 2012-11-07T06:23:37.997 回答
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);
    }
}
于 2012-11-07T08:37:41.617 回答