【问题标题】:How many seconds from midnight until specific Datetime从午夜到特定日期时间的秒数
【发布时间】:2015-03-30 08:54:33
【问题描述】:

有没有一种很好的简单速记方法来找出某个日期时间在午夜过后多少秒?不是离现在还有多少秒,是那天过去的几秒

例如:

  • 2015-04-10 00:00:00 应该返回 0
  • 2015-04-12 09:20:00 应该返回 33600
  • 2015-04-14 15:20:00 应该返回 55200

有没有一个很好的简短方法来做到这一点?

【问题讨论】:

  • 为什么不直接提取小时、分钟和秒并计算(小时*60+分钟)*60+秒?或者您的时间戳到底是什么格式?
  • 它是显示的格式。我原来的方法是做类似 mktime(0,0,0,strtotime(date('m',$stamp)),strtotime(date('d',$stamp)),strtotime(date('Y', $stamp))) - 但我想知道是否有速记版本

标签: php datetime time timestamp


【解决方案1】:

这是一个简单的代码。

任何一天的代码

<?php
$date = "2015-04-12 09:20:00";

$midnight = strtotime(date("Y-m-d 00:00:00", strtotime($date)));
$now = strtotime($date);

$diff = $now - $midnight;
echo $diff;
?>

当天代码

<?php
$midnight = strtotime("midnight");
$now = date('U');

$diff = $now - $midnight;
echo $diff;
?>

也许更简洁的代码是使用strtotime("midnight", &lt;EpochTime&gt;);

<?php
$date = "2015-04-12 09:20:00";

$midnight = strtotime("midnight", strtotime($date));
$now = strtotime($date);

$diff = $now - $midnight;
echo $diff;
?>

【讨论】:

  • 我已经重新接受这个作为任何未来用户的答案,因为它可能更接近我使用的方法
【解决方案2】:

一天是 24 小时是 60 分钟是 60 秒是 1000 毫秒,所以时间戳 % (24*60*60*1000) 可以工作,也许,至少如果你在同一时区作为 php 是使用(或任何你的时间戳来自)。它至少可以在对准确性要求不高的情况下工作。 PHP 使用您系统的时间,所以很多事情都会打破这个想法(更改时钟、DST、闰秒等)

我个人会使用时间戳 - startofday 时间戳,并使用该语言的日历进行计算。

【讨论】:

  • 啊,这实际上对我有所帮助,特别是最后一句话,我不知道您可以执行 strtotime("midnight", $stamp) 来获取日期戳的午夜,这正是我所做的之后。
猜你喜欢
  • 2012-10-03
  • 2011-06-09
  • 2012-12-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多