PHP中用于计算指定格式的两个日期之间的天数差异的最佳(日期格式无关方式).
我尝试了以下功能:
function get_date_offset($start_date, $end_date) { $start_time = strtotime($start_date); $end_time = strtotime($end_date); return round(($end_time-$start_time)/(3600*24)); }
它在linux机箱上运行正常,但在windows下运行strtotime会返回''.
编辑:
输入日期是mm/dd/yyyy格式,但我想让它接受$ format作为参数.
我只需要几天的差异.
如果您不想要或者您不能使用Zend Framework或Pear包试试这个功能,我希望这会有所帮助:
function dateDifference($date1, $date2) { $d1 = (is_string($date1) ? strtotime($date1) : $date1); $d2 = (is_string($date2) ? strtotime($date2) : $date2); $diff_secs = abs($d1 - $d2); $base_year = min(date("Y", $d1), date("Y", $d2)); $diff = mktime(0, 0, $diff_secs, 1, 1, $base_year); return array ( "years" => abs(substr(date('Ymd', $d1) - date('Ymd', $d2), 0, -4)), "months_total" => (date("Y", $diff) - $base_year) * 12 + date("n", $diff) - 1, "months" => date("n", $diff) - 1, "days_total" => floor($diff_secs / (3600 * 24)), "days" => date("j", $diff) - 1, "hours_total" => floor($diff_secs / 3600), "hours" => date("G", $diff), "minutes_total" => floor($diff_secs / 60), "minutes" => (int) date("i", $diff), "seconds_total" => $diff_secs, "seconds" => (int) date("s", $diff) ); }