给定一个Unix时间戳,如何开始和结束那一天


Given a Unix timestamp, how to get beginning and end of that day?

我有一个像这样的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;

也可以使用日期时间,但需要一些额外的步骤才能从长时间戳中获取

$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 检查,可能会错过一秒钟。使用$now < $nextStart检查可以避免这种差距,此外还有在PHP的时间处理中减去秒和夏令时的奇怪之处。

Just DateTime

$beginOfDay = DateTime::createFromFormat('Y-m-d H:i:s', (new DateTime())->setTimestamp($timestamp)->format('Y-m-d 00:00:00'))->getTimestamp();
$endOfDay = DateTime::createFromFormat('Y-m-d H:i:s', (new DateTime())->setTimestamp($timestamp)->format('Y-m-d 23:59:59'))->getTimestamp();

首先创建一个 DateTime 对象,并将时间戳设置为所需的时间戳。然后将对象格式化为字符串,将小时/分钟/秒设置为一天的开始或结束。最后,从此字符串创建一个新的 DateTime 对象并检索时间戳。

$dateTimeObject = new DateTime();
$dateTimeObject->setTimestamp($timestamp);
$beginOfDayString = $dateTimeObject->format('Y-m-d 00:00:00');
$beginOfDayObject = DateTime::createFromFormat('Y-m-d H:i:s', $beginOfDayString);
$beginOfDay = $beginOfDayObject->getTimestamp();

我们可以使用此较长版本以替代方式结束一天:

$endOfDayObject = clone $beginOfDayOject(); // Cloning because add() and sub() modify the object
$endOfDayObject->add(new DateInterval('P1D'))->sub(new DateInterval('PT1S'));
$endOfDay = $endOfDayOject->getTimestamp();

时区

也可以通过在创建 DateTime 对象后将时间戳指示器添加到格式(如 O)并指定时间戳来设置时区:

$beginOfDay = DateTime::createFromFormat('Y-m-d H:i:s O', (new DateTime())->setTimezone(new DateTimeZone('America/Los_Angeles'))->setTimestamp($timestamp)->format('Y-m-d 00:00:00 O'))->getTimestamp();

日期时间的灵活性

我们还可以通过更改指定的第二种格式来获取其他信息,例如月初/月末或一小时的开始/结束。月份:'Y-m-01 00:00:00''Y-m-t 23:59:59'。小时:'Y-m-d H:00:00''Y-m-d H:59:59'

将各种格式与 add()/sub() 和 DateInterval 对象结合使用,我们可以获取任何周期的开始或结束,尽管需要注意正确处理闰年。

相关链接

从 PHP 文档中:

  • 日期时间
  • 包含格式信息的日期
  • 日期时区
  • 日期间隔

您可以使用date()mktime()的组合:

list($y,$m,$d) = explode('-', date('Y-m-d', $ts));
$start = mktime(0,0,0,$m,$d,$y);
$end = mktime(0,0,0,$m,$d+1,$y);

mktime()足够聪明,可以在指定月份之外的一天(1 月 32 日将是 2 月 1 日等)时包装月份/年份

您可以将时间转换为当前数据,然后使用 strtotime 函数查找一天的开始,只需将 24 小时添加到其中即可找到一天的结束。

您还可以使用余数运算符 (%) 来查找最近的日期。例如:

$start_of_day = time() - 86400 + (time() % 86400);
$end_of_day = $start_of_day + 86400;

不幸的是,由于在非常特定的情况下发生的 php 错误,接受的答案被打破了。我将讨论这些场景,但首先使用日期时间给出答案。这和接受的答案之间的唯一区别发生在// IMPORTANT行之后:

$dtNow = new DateTime();
// Set a non-default timezone if needed
$dtNow->setTimezone(new DateTimeZone('America/Havana'));
$dtNow->setTimestamp($timestamp);
$beginOfDay = clone $dtNow;
// Go to midnight.  ->modify('midnight') does not do this for some reason
$beginOfDay->modify('today');
// now get the beginning of the next day
$endOfDay = clone $beginOfDay;
$endOfDay->modify('tomorrow');
// IMPORTANT
// get the timestamp
$ts = $endOfDay->getTimestamp();
// subtract one from that timestamp
$tsEndOfDay = $ts - 1;
// we now have the timestamp at the end of the day. we can now use that timestamp
// to set our end of day DateTime
$endOfDay->setTimestamp($tsEndOfDay);

所以你会注意到,我们没有使用->modify('1 second ago');而是得到时间戳并减去一个。使用 modify 的接受答案应该有效,但在非常特定的情况下会因为 php 错误而中断。此错误发生在在午夜更改夏令时的时区中,即时钟"向前"移动的一年中的某一天。下面是可用于验证该 bug 的示例。

错误示例代码

// a time zone, Cuba, that changes their clocks forward exactly at midnight. on
// the day before they make that change. there are other time zones which do this
$timezone = 'America/Santiago';
$dateString = "2020-09-05";
echo 'the start of the day:<br>';
$dtStartOfDay = clone $dtToday;
$dtStartOfDay->modify('today');
echo $dtStartOfDay->format('Y-m-d H:i:s');
echo ', '.$dtStartOfDay->getTimestamp();
echo '<br><br>the start of the *next* day:<br>';
$dtEndOfDay = clone $dtToday;
$dtEndOfDay->modify('tomorrow');
echo $dtEndOfDay->format('Y-m-d H:i:s');
echo ', '.$dtEndOfDay->getTimestamp();
echo '<br><br>the end of the day, this is incorrect. notice that with ->modify("-1 second") the second does not decrement the timestamp by 1:<br>';
$dtEndOfDayMinusOne = clone $dtEndOfDay;
$dtEndOfDayMinusOne->modify('1 second ago');
echo $dtEndOfDayMinusOne->format('Y-m-d H:i:s');
echo ', '.$dtEndOfDayMinusOne->getTimestamp();
echo '<br><br>the end of the day, this is correct:<br>';
$dtx = clone $dtEndOfDay;
$tsx = $dtx->getTimestamp() - 1;
$dty = clone $dtEndOfDay;
$dty->setTimestamp($tsx);
echo $dty->format('Y-m-d H:i:s');
echo ', '.$tsx;

错误示例代码输出

the start of the day:
2020-03-26 00:00:00, 1585173600
the start of the *next* day:
2020-03-27 01:00:00, 1585260000
the end of the day, this is incorrect. notice that with ->modify("1 second ago") the
second does not decrement the timestamp by 1:
2020-03-27 01:59:59, 1585263599
the end of the day, this is correct:
2020-03-26 23:59:59, 1585259999

今天开始日期时间戳。简单

$stamp = mktime(0, 0, 0);
echo date('m-d-Y H:i:s',$stamp);
$start_of_day = floor (time() / 86400) * 86400;
$end_of_day = ceil (time() / 86400) * 86400;

如果需要在同一脚本中同时使用这两个值。对其中一个变量进行 +/- 86400 秒比同时发射地板和 ceil 更快。例如:

$start_of_day = floor (time() / 86400) * 86400;
$end_of_day = $start_of_day + 86400;

对于将来有这个问题的任何人:

任何日期代码

<?php
$date = "2015-04-12 09:20:00";
$midnight = strtotime("midnight", strtotime($date));
$now = strtotime($date);
$diff = $now - $midnight;
echo $diff;
?>

当日代码

<?php
$midnight = strtotime("midnight");
$now = date('U');
$diff = $now - $midnight;
echo $diff;
?>
$date = (new 'DateTime())->setTimestamp(1330581600);
echo $date->modify('today')->format('Y-m-d H:i:s'); // 2012-02-29 00:00:00
echo PHP_EOL;
echo $date->modify('tomorrow - 1 second')->format('Y-m-d H:i:s'); // 2012-02-29 23:59:59
    $startOfDay = new 'DateTime('tomorrow');
    $startOfDay->modify('-1 day');

这对我有用:)

派对有点晚了,但这是实现您正在寻找的另一种简单方法:

$timestamp=1330581600;
$format = DATE_ATOM;
$date = (new DateTime())->setTimestamp($timestamp);
// Here's your initial date, created from the timestamp above
// 2012-03-01T06:00:00+00:00
$dateFromTimestamp = $date->format($format);
// This is the beginning of the day
// 2012-03-01T00:00:00+00:00
$startOfDay = $date->setTime(0,0);
// This is the beginning of the next day
// 2012-03-02T00:00:00+00:00
$startOfNextDay = $startOfDay->modify('+1 day');

除非绝对必要,否则我个人会避免使用一天结束时。当然,您可以使用23:59:59但这不是一天的实际结束(还剩下 1 秒)。我所做的是使用第二天的开始作为我的结束边界,例如:

$start = new DateTime('2021-11-09 00:00:00');
$end = new DateTime('2021-11-10 00:00:00');
    
if ($someDateTime >= $start && $someDateTime < $end) {
    // do something
}

如果我必须使用一天的结束,我会计算第二天的开始,然后从中减去 1 微秒

$beginOfDay = (new DateTime('today', new DateTimeZone('Asia/Tehran')))->getTimestamp();
$endOfDay   = $beginOfDay + 86399;

您可以通过替换"亚洲/德黑兰"来设置时区。一天是86400秒,不要问我为什么是86399,是我脑海中的低语说是86399,所以我甚至不想去想它的真相。