PHP日期转换

时间:2012-11-07 06:20:51

标签: php datetime

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

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

4 个答案:

答案 0 :(得分:2)

因为您正在将$date从“1990-05-07”更改为“07/05/1990”。您已将其从Y-m-d更改为d/m/Y,解析器将其识别为m/d/Y。你不能重复使用第一个日期调用的resule,因为它不会按你想象的那样解析。

解决方案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

答案 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);
    }
}