php - 在 PHP 中,如何获得两个时间戳之间的准确(非近似)总周数、月数和年数?
问题描述
我可以这样做几天:
$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) .'' ;
}
}
}
推荐阅读
- grafana - 如何在 grafana 世界地图面板中显示来自石墨的坐标
- javascript - 为什么我在尝试发布到表单时收到无法发布 /api/ 错误?
- firebase - 如何始终获取最新的 Firebase 身份验证令牌
- ios - 如何使用 XCUITest 自动化 googleSignIn POD 的 gmail 登录
- node.js - MongDB 内存消耗高于wiredTigercacheSizeGB 中设置的值
- firebase - 如何在 Firebase 中使用 GitHub 应用程序“安装期间的身份验证”
- windows - 如何更改 DateTime Picker 控件的背景颜色?
- python - 优化随机卡片分配
- snyk - Snyk 测试返回 Failed to test pip 项目错误
- angular - Angular 更新破坏了 Tailwindcss