获取特定提供日期的午夜时间戳

时间:2014-12-31 08:01:58

标签: php strtotime

我有一个像这样的日期

$given_date = '2014-12-25'; //Y-m-d format

现在我想得到给定日期的午夜时间戳,所以我正在做这个方法

$midnight = strtotime(date('Y-m-d',$given_date).' 00:00:00');

我做得对吗?

或者我可以使用这样的东西?

$midnight = strtotime("midnight $given_date");

哪个更好?

3 个答案:

答案 0 :(得分:12)

我更倾向于使用更多OO方法而不是摆弄字符串:

$date = new DateTime($given_date);
$date->setTime(0,0,0);

// echo $date->format('Y-m-d H:i:s');
echo $date->getTimestamp();

答案 1 :(得分:0)

也可以使用:

list($y, $m, $d) = explode('-', $given_date);
$midnight = mktime(0, 0, 0, $m, $d, $y);

答案 2 :(得分:0)

使用来自DateTime的静态方法createFromFormat,您可以使用“|”强制将时间部分重置为0:

$date = DateTime::createFromFormat('Y-m-d|', $given_date);
echo $date->format('Y-m-d H:i:s');
相关问题