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


Date is incorrect, displays Dec 31, 1969

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

所以,我真的不知道出了什么问题。我有其余的代码也需要查看。我该如何解决此问题以显示正确的日期。

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

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

如果您将其作为字符串传递,请尝试此操作

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

注意 strtotime() 函数