這裏是我到目前爲止有:如何計算兩天之間的差異作爲格式化的字符串?
/**
* 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君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
被忽略,分鐘應該被滾動到秒
如果「更小的單位」被省略,下一個最大的單位可以被舍入或地板有意義的地方。
如果你有PHP 5.3.0或以上,這可以幫助你:[DateInterval ::格式(http://www.php.net/manual/en/dateinterval.format.php) – drew010
重複[this post](http:// stackoverflow。com/questions/676824/how-to-calculate-the-difference-between-dates-using-php) – bowlerae
@ drew010:不......不能處理數週。 – mpen