[英]In PHP, how do I get the accurate (not approximate) total individual number of weeks, months and years between two timestamps?
我可以这样做几天:
$d1 = new DateTime('2000-01-01 12:00:00');
$d2 = new DateTime('2020-01-01 12:00:00');
$diff = $d2->diff($d1);
echo $diff->days;
换句话说,它可以工作几天。 但是,DateTime/ DateInterval类只有一个 $days 变量——这些是预期的,但不存在:
$diff->weeks;
$diff->months;
$diff->years;
阅读手册,您乍一看可能会误以为它确实具有以下属性: https : //www.php.net/manual/en/class.dateinterval.php
public integer $y ;
public integer $m ;
public integer $d ;
public integer $h ;
public integer $i ;
public integer $s ;
public float $f ;
public integer $invert ;
public mixed $days ;
y, m, d, h, i, s不是“个体总数”,而是相互依赖。 例如,如果时间跨度正好是一年,则 $y 将为 1,但所有其他的将为 0,而不是它们各自的表示(12 个月、52 周等)。
由于某些原因,他们通过包含 $days 变量来特别对待天数,该变量确实显示了实际的总天数。 我也想要数周、数月和数年。
我已经知道如何“估计”两个时间戳之间的周数/月数/年数,方法是使用简单的数学和固定变量来表示每个时间单位的平均秒数。 由于这没有考虑到“遍历”日历格式的所有复杂性,例如闰年、不同月份的不同天数以及许多其他小/复杂的细节,因此您无法获得确切的数字道路。
我想知道两个时间戳之间的确切总周数,以及年和月相同的事情,彼此独立。
这将返回两天之间的确切差异,希望这对您有所帮助。
$time_diffrence=getDiffrenceBetweenTwoDays($date1,$date2);
function getDiffrenceBetweenTwoDays($date1,$date2){
$etime = strtotime($date1) - strtotime($date2;
if ($etime < 1)
{
return '0 seconds';
}
$a = array( 365 * 24 * 60 * 60 => 'year',
30 * 24 * 60 * 60 => 'month',
24 * 60 * 60 => 'day',
60 * 60 => 'hour',
60 => 'minute',
1 => 'second'
);
$a_plural = array( 'year' => 'years',
'month' => 'months',
'day' => 'days',
'hour' => 'hours',
'minute' => 'minutes',
'second' => 'seconds'
);
foreach ($a as $secs => $str)
{
$d = $etime / $secs;
if ($d >= 1)
{
$r = round($d);
return $r . ' ' . ($r > 1 ? $a_plural[$str] : $str) .'' ;
}
}
}
在此链接中将 %a 替换为以下任何一项:
$d1 = date_create('2000-01-01 12:00:00');
$d2 = date_create('2020-01-01 12:00:00');
$diff = date_diff($d1, $d2);
$days = $diff->format('%a');
echo $days; // 7305
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.