这是我到目前为止所得到的:
/**
* Parse a duration between 2 date/times in seconds
* and to convert that duration into a formatted string
*
* @param integer $time_start start time in seconds
* @param integer $time_end end time in seconds
* @param string $format like the php strftime formatting uses %y %m %w %d %h or %i.
* @param boolean $chop chop off sections that have 0 values
*/
public static function FormatDateDiff($time_start = 0, $time_end = 0, $format = "%s", $chop = false) {
if($time_start > $time_end) list($time_start, $time_end) = array($time_end, $time_start);
list($year_start,$month_start,$day_start) = explode('-',date('Y-m-d',$time_start));
list($year_end,$month_end,$day_end) = explode('-',date('Y-m-d',$time_end));
$years = $year_end - $year_start;
$months = $month_end - $month_start;
$days = $day_start - $day_end;
$weeks = 0;
$hours = 0;
$mins = 0;
$secs = 0;
if(mktime(0,0,0,$month_end,$day_end) < mktime(0,0,0,$month_start,$day_start)) {
$years -= 1;
}
if($days < 0) {
$months -= 1;
$days += 30; // this is an approximation...not sure how to figure this out
}
if($months < 0) $months += 12;
if(strpos($format, '%y')===false) {
$months += $years * 12;
}
if(strpos($format, '%w')!==false) {
$weeks = floor($days/7);
$days %= 7;
}
echo date('Y-m-d',$time_start).' to '.date('Y-m-d',$time_end).": {$years}y {$months}m {$weeks}w {$days}d<br/>";
}
(不完整且不准确)
我似乎无法正确计算。由于闰年和不同的月份长度,天真地把它分开是行不通的。
逻辑还需要根据格式字符串进行更改。例如,使用格式字符串将 04-Feb-2010 传递到 28-Jun-2011(作为 unix 时间戳)%y year %m month %d day
应该输出1 year 4 month 24 day
,但如果%y year
省略,则需要在月份中添加 12 个月,即输出应该是16 month 24 day
.
也应该处理时间......但我还没有做到这一点。
这些date_diff解决方案都没有处理周数。而且我不知道如何破解它date_diff
,所以这对我来说并不是一个真正的解决方案。
此外,$diff->format
如果省略“更大的单位”,则不会按照我的要求...给出总月数和天数。例子:
>>> $start = new DateTime('04-Feb-2010')
>>> $end = new DateTime('28-Jun-2011')
>>> $diff = $start->diff($end)
>>> $diff->format('%m months, %d days')
'4 months, 24 days'
应该是16 months, 24 days
,正如我之前所说。在你完全理解之前,请不要这么快就结束我的问题。如果可以调整其他问题的解决方案来解决这个问题,那很好,但请解释一下如何,因为我不明白。
要清楚,
- 如果
%y
省略,则应在月份中滚动年份 - 如果
%m
省略,则应将月份滚动到天数中 - 如果
%w
省略,则应将周滚动到天 - 如果
%h
省略,小时应转换为分钟 - 如果
%m
省略,分钟应该滚动到秒
如果省略“较小的单元”,则下一个最大的单元可以在有意义的地方进行四舍五入或地板化。