日期不正确,显示1969年12月31日

时间:2013-11-01 03:56:26

标签: php

function convertdate($date) {
date_default_timezone_set('America/Chicago');
return date("M j, Y g:ia", $date);
}

所以,我真的不知道出了什么问题。我还需要查看其余的代码。我怎么能解决这个问题才能显示正确的日期。

2 个答案:

答案 0 :(得分:1)

PHP的date函数将整数时间戳(自1970-01-01 UTC以来的秒数)作为其第二个参数。我的猜测是你没有向你的函数传递一个整数(或者至少不是正确的整数)。

请尝试使用DateTime,例如

function convertDate($date) {
    $dt = new DateTime($date, new DateTimeZone('America/Chicago'));
    return $dt->format('M j, Y g:ia');
}

在这里演示 - http://codepad.viper-7.com/EUXgwJ

DateTime构造函数中的日期字符串解析在某种程度上是美国语言环境特定的(例如默认情况下为mm / dd / yyyy)。您可以通过指定要在DateTime::createFromFormat中使用的可选格式参数来获得更好的里程,例如

function convertDate($date, $format = null) {
    $tz = new DateTimeZone('America/Chicago');
    if ($format !== null) {
        $dt = DateTime::createFromFormat($format, $date, $tz);
        if ($dt === false) {
            throw new Exception('Could not parse date / time string');
        }
    } else {
        $dt = new DateTime($date, $tz);
    }
    return $dt->format('M j, Y g:ia');
}

现在你可以让DateTime对日期/时间字符串进行最佳猜测,或者明确告诉它使用哪种格式,例如

echo convertDate('1/11/2013', 'd/m/Y');

演示#2 - http://codepad.viper-7.com/gMjYLO

答案 1 :(得分:0)

你在$date变量中传递了什么。

如果您将其作为字符串传递

,请尝试此操作
function convertdate($date) {
  date_default_timezone_set('America/Chicago');
  return date("M j, Y g:ia", strtotime($date));
}                              ^^^^

注意strtotime()函数

相关问题