为什么date()返回一个意外的值?

时间:2013-12-10 01:27:50

标签: php date datetime foreach

这是一个名为var_dump的数组的$events

array (size=3)
  0 => 
    array (size=4)
      'weekday' => string '0' (length=1)
      'start_time' => string '2013-12-09 12:00:00' (length=19)
      'name' => string 'Lunch' (length=5)
      'location' => string '1' (length=1)
  1 => 
    array (size=4)
      'weekday' => string '0' (length=1)
      'start_time' => string '2013-12-09 17:00:00' (length=19)
      'name' => string 'Dinner' (length=6)
      'location' => string '3' (length=1)
  2 => 
    array (size=4)
      'weekday' => string '1' (length=1)
      'start_time' => string '2013-12-09 08:00:00' (length=19)
      'name' => string 'Breakfast' (length=9)
      'location' => string '2' (length=1)

当我运行以下内容时:

foreach ($events as $event) {
    echo $event['start_time'] . ', ' . date('g:i a', $event['start_time']);
}

这是我得到的:

2013-12-09 12:00:00, 4:33pm
2013-12-09 17:00:00, 4:33pm
2013-12-09 08:00:00, 4:33pm

我希望:

2013-12-09 12:00:00, 12:00pm
2013-12-09 17:00:00, 5:00pm
2013-12-09 08:00:00, 8:00am

为什么每次调用date()都会返回相同的值?

2 个答案:

答案 0 :(得分:4)

需要将放入date()函数的日期作为unix时间戳。

foreach ($events as $event) {
    echo $event['start_time'] . ', ' . date('g:i a', strtotime($event['start_time']));
}

答案 1 :(得分:0)

date()的第二个参数应该是一个数字时间戳。相反,你给它一个完整的日期,它试图解析为一个数字。从那里它获得2013秒,这是33分钟& 33秒在UTC-8时区,在前一天下午4点后33分钟出来......基本上它会导致无意义。

尝试在字符串上使用strtotime

echo $event['start_time'] . ', ' . date('g:i a', strtotime($event['start_time']));