$diff = abs(strtotime($date2) - strtotime($date1));
将月份和天数数量按要求输出:
$res = 4.05 //-> 4 months and 5 days
$diff = abs(strtotime($date2) - strtotime($date1));
将月份和天数数量按要求输出:
$res = 4.05 //-> 4 months and 5 days
可能有类似这样的解决方案。我的数学可能有点偏差。
$diff = abs(strtotime($date2) - strtotime($date1));
define('DAY',60*60*24, true);
define('MONTH',DAY*30, true);
define('YEAR',DAY*365, true);
$years = floor($diff / (YEAR));
$months = floor(($diff - $years * YEAR) / (MONTH));
$days = floor(($diff - $years * YEAR - $months*MONTH ) / (DAY));
你不能这样处理,因为月份的长度会有所不同,除非你想基于平均月份长度做出假设。如果您想要正确的差异,您需要使用实际日期,然后可以使用PHP的date_diff函数 - http://www.php.net/manual/en/datetime.diff.php
如果您使用的是PHP 5.3,您可能需要使用
http://de.php.net/manual/en/datetime.diff.php
如果您使用的是更低版本的PHP,则可以使用类似以下的方法: (简单解决方案,不是最快或最好的)
$days = 0;
$months = 0;
$month = date("n", $time1);
while ($time1 < $time2)
{
++$days;
if (date("n", $time1) != $month)
{
$month = date("n", $time1);
$days = 0;
$months++;
}
$time1 = mktime(0, 0, 0, date("n", $time1), date("j", $time1) + 1, date("Y"));
}
//免责声明:未经测试
时间戳实际上是自Unix纪元开始的秒数,即1970年1月1日。因此,时间戳之间的差异实际上是以秒为单位的。因此,要将秒转换为天,您只需将其除以一天的秒数,即$Timestamp/(24x60x60)。同样适用于一个月的情况,$ Timestamp /(24x60x60x30)
function diff_date_day($day , $month , $year , $day2 , $month2 , $year2){
$timestamp = mktime(0, 0, 0, $month, $day, $year, 0);
$timestamp2 = mktime(0, 0, 0, $month2, $month2, $year2);
$diff = floor(($timestamp - $timestamp2) / (3600 * 24));
return $diff;
}
假设一个月平均为30天,然后计算月数。这对于一些需求可能足够(例如显示博客评论的年龄等),但对于其他需求则完全不适用。
我认为在php中没有这个功能。因此,您将不得不使用整数除法(或普通除法)和模运算符。
例如(示例使用小时而不是毫秒,但重复的技巧相同):
$totalhours = 27;
$days = round($totalhours / 24);
$hours = $totalhours % 24;
这将给出 $days = 1 和 $hours = 3。
如其他回复所述,找到月份更难,因为每个月的天数不是固定的。
我知道这已经过时了,但当我在寻找一些东西来计算给定时间戳格式的出生日期与当前日期之间的时间差(以“3年6个月”的格式)时,我偶然发现了这篇文章。我写了下面的代码,希望对某些人有所帮助。
// Determine age
$time_start = 'YOUR DOB';
$time_end = strtotime('today');
$years = 0;
$months = 0;
while ($time_start < $time_end){
$tmp_time = strtotime('+ 1 year', $time_start);
if ($tmp_time < $time_end){
$years++;
$time_start = $tmp_time;
} else {
$tmp_time = strtotime('+ 1 month', $time_start);
if ($tmp_time < $time_end){
$months++;
$time_start = $tmp_time;
} else {
$time_start = $time_end;
}
}
}
$age = $years.' years & '.$months.' months';
找到了一个使用MySQL计算月份的解决方案:
SELECT TIMESTAMPDIFF(MONTH,'{$start_time_str}','{$end_time_str}') AS m
感谢所有参与其中的人。