【问题标题】:Problems with finding the days between two unix timestamps查找两个 unix 时间戳之间的日期的问题
【发布时间】:2013-03-08 20:11:54
【问题描述】:

我已经知道有很多关于这个的问题和答案,但不幸的是我认为我的情况可能是独一无二的?出于某种原因,时间变化似乎使一天计算为比应计算的少一天。

这是我正在使用的 PHP,它运行良好,直到它开始分别与夏令时之前和夏令时之后的开始日期和结束日期重叠(仅供参考,这是一个最近的问题,因为夏令时节省时间从本周末开始!):

//$lastDate and $firstDate are 2 unix timestamps with valid month, day, and year values.
//The times are irrelevant at this point, they are only meant to represent a day.

//I start by making sure these have the same time values.
$lastDate = mktime(23, 59, 59, date("m", $lastDate), date("j", $lastDate), date("Y", $lastDate));
$firstDate = mktime(23, 59, 59, date("m", $firstDate), date("j", $firstDate), date("Y", $firstDate));

//Then calculate the total number of days in between.
$totalDays = abs(floor(($firstDate - $lastDate)/(60*60*24)));

再次说明,如果我不重叠夏令时更改,则上述方法有效...

供参考:

How to find the dates between two specified date?

Actual days between two unix timestamps in PHP

Finding days between 2 unix timestamps in php

而且,我现在还在使用 PHP 5.2。

编辑/更新:
我在这个链接上找到了以下内容:

How to find the dates between two specified date?

和

How to calculate the the interval between 2 unix timestamps in php WITHOUT dividing by 86400 (60*60*24)

//$lastDate and $firstDate are 2 unix timestamps with valid month, day, and year values.
//The times are irrelevant at this point, they are only meant to represent a day.

//I start by making sure these have the same time values.
$lastDate = mktime(10, 00, 00, date("m", $lastDate), date("j", $lastDate), date("Y", $lastDate));
$firstDate = mktime(10, 00, 00, date("m", $firstDate), date("j", $firstDate), date("Y", $firstDate));

//Then calculate the total number of days in between. 
$totalDays = floor($firstDate / 86400) - floor($lastDate/ 86400);

而且它现在似乎适用于 DST 的交叉。有人看到这有什么问题吗?

【问题讨论】:

  • stackoverflow.com/questions/2674918/… 我会使用新的dateTime 并在可能的情况下下车 5.2。否则请务必查看 mktime 的 is_dst 参数。
  • @ficuscr hmmm,所以 DateTime 毕竟是在 5.2 中,出于某种原因,我认为它只是在 5.3 中。
  • 我认为有一些fixes and improvements 进入了 5.3。 DateInterval 类例如。但它就在那里。
  • @ficuscr 我是否需要在每次页面加载时设置时区/对象,即我可以在所有这些页面上调用 session_start 的同一位置执行此操作?
  • @ficuscr 好的,所以这对我来说效果不佳 =)。 is_dst 从 5.1 开始折旧。我不能使用 DateTime 类,因为 diff 函数在 5.2 中不可用。这里有什么想法吗?

标签: php unix-timestamp dst


【解决方案1】:

您是否在 PHP 5.3+ 上运行? DateInterval 非常适合这个问题。
http://www.php.net/manual/en/datetime.diff.php

<?php
$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');

【讨论】:

  • 这是问题...我有 unix 时间戳开始。我可以使用时间戳作为 DateTime 的参数,即DateTime($timeStamp1)吗?
  • @Shackrock 是的,使用DateTime('@' . $timestamp)(注意@符号)
  • @ColinMorelli 好的,现在你让我有点困惑。我的时间戳应该是一个绝对的日期和时间,对吧?那么 28 天与任何事情有什么关系,除非我碰巧在 2 月份内?
  • @ColinMorelli 如果您在格式中使用 %a 则不会。它返回总天数。
  • @landons Touche,我删除了我的评论。
猜你喜欢
  • 1970-01-01
  • 2022-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-06
  • 2014-05-22
  • 2014-07-12
  • 2020-07-19
相关资源
最近更新 更多