efr*_*itz 91 php datetime date
计算两个日期之间总秒数的最佳方法是什么?到目前为止,我已尝试过以下方面:
$delta = $date->diff(new DateTime('now'));
$seconds = $delta->days * 60 * 60 * 24;
Run Code Online (Sandbox Code Playgroud)
但是,daysDateInterval对象的属性似乎在当前的PHP5.3版本中被破坏(至少在Windows上,它总是返回相同的6015值).我还试图以一种不能保存每个月(轮数到30天),闰年等天数的方式来做到这一点:
$seconds = ($delta->s)
+ ($delta->i * 60)
+ ($delta->h * 60 * 60)
+ ($delta->d * 60 * 60 * 24)
+ ($delta->m * 60 * 60 * 24 * 30)
+ ($delta->y * 60 * 60 * 24 * 365);
Run Code Online (Sandbox Code Playgroud)
但是我真的不满意使用这种半成品解决方案.
Ben*_*Ben 190
你不能比较时间戳吗?
$now = new DateTime('now');
$diff = $date->getTimestamp() - $now->getTimestamp()
Run Code Online (Sandbox Code Playgroud)
dav*_*010 32
此函数允许您从DateInterval对象获取总持续时间(以秒为单位)
/**
* @param DateInterval $dateInterval
* @return int seconds
*/
function dateIntervalToSeconds($dateInterval)
{
$reference = new DateTimeImmutable;
$endTime = $reference->add($dateInterval);
return $endTime->getTimestamp() - $reference->getTimestamp();
}
Run Code Online (Sandbox Code Playgroud)
DateTime::diff返回DateInterval2 个日期之间的对象。
该DateInterval对象提供了所有信息(天数、小时数、分钟数、秒数)。
这是示例代码:
/**
* intervalToSeconds
*
* @param DateInterval $interval
* @return int
*/
function intervalToSeconds(\DateInterval $interval) {
return $interval->days * 86400 + $interval->h * 3600 + $interval->i * 60 + $interval->s;
}
$date_1 = new \DateTime('2021-03-03 05:59:19');
$date_2 = new \DateTime('now');
$interval = $date_1->diff($date_2);
echo intervalToSeconds($interval);
Run Code Online (Sandbox Code Playgroud)
你可以这样做:
$currentTime = time();
$timeInPast = strtotime("2009-01-01 00:00:00");
$differenceInSeconds = $currentTime - $timeInPast;
Run Code Online (Sandbox Code Playgroud)
time()返回自纪元时间(1970-01-01T00:00:00)以来的当前时间(秒),并且strtotime执行相同的操作,但是基于您给出的特定日期/时间.
小智 5
static function getIntervalUnits($interval, $unit)
{
// Day
$total = $interval->format('%a');
if ($unit == TimeZoneCalc::Days)
return $total;
//hour
$total = ($total * 24) + ($interval->h );
if ($unit == TimeZoneCalc::Hours)
return $total;
//min
$total = ($total * 60) + ($interval->i );
if ($unit == TimeZoneCalc::Minutes)
return $total;
//sec
$total = ($total * 60) + ($interval->s );
if ($unit == TimeZoneCalc::Seconds)
return $total;
return false;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
62308 次 |
| 最近记录: |