我有这样一个Unix时间戳:
$timestamp=1330581600
我如何获取该时间戳的一天的开始和一天的结束?
e.g.
$beginOfDay = Start of Timestamp's Day
$endOfDay = End of Timestamp's Day
我试过这个:
$endOfDay = $timestamp + (60 * 60 * 23);
但我认为它不会起作用,因为时间戳本身并不是一天的确切开始.
我有这样一个Unix时间戳:
$timestamp=1330581600
我如何获取该时间戳的一天的开始和一天的结束?
e.g.
$beginOfDay = Start of Timestamp's Day
$endOfDay = End of Timestamp's Day
我试过这个:
$endOfDay = $timestamp + (60 * 60 * 23);
但我认为它不会起作用,因为时间戳本身并不是一天的确切开始.
strtotime可以用来快速地砍掉小时/分钟/秒
$beginOfDay = strtotime("today", $timestamp);
$endOfDay = strtotime("tomorrow", $beginOfDay) - 1;
DateTime也可以使用,不过从长时间戳中获取数据需要额外的几个步骤
$dtNow = new DateTime();
// Set a non-default timezone if needed
$dtNow->setTimezone(new DateTimeZone('Pacific/Chatham'));
$dtNow->setTimestamp($timestamp);
$beginOfDay = clone $dtNow;
$beginOfDay->modify('today');
$endOfDay = clone $beginOfDay;
$endOfDay->modify('tomorrow');
// adjust from the start of next day to the end of the day,
// per original question
// Decremented the second as a long timestamp rather than the
// DateTime object, due to oddities around modifying
// into skipped hours of day-lights-saving.
$endOfDateTimestamp = $endOfDay->getTimestamp();
$endOfDay->setTimestamp($endOfDateTimestamp - 1);
var_dump(
array(
'time ' => $dtNow->format('Y-m-d H:i:s e'),
'start' => $beginOfDay->format('Y-m-d H:i:s e'),
'end ' => $endOfDay->format('Y-m-d H:i:s e'),
)
);
在PHP7中增加了延长时间,如果使用$now <= $end
判断,可能会错过一秒钟.