我想问一个关于这篇文章中给出的答案的问题(如何获得360天/年、30天/月格式的两个日期之间的差异?(我无法对此发表评论,因为我没有必要的声誉。提供的功能
function diff360($date1, $date2) {
$date1 = new DateTime($date1);
$date2 = new DateTime($date2);
$diff = $date1->diff($date2);
$days = ($date2->format('d') + 30 - $date1->format('d')) % 30;
return array(
"y" => $diff->y,
"m" => $diff->m,
"d" => $days,
"totaldays" => $diff->y * 360 + $diff->m * 30 + $days
);
}
通常工作良好,除了某些情况,例如CCD_;0年9个月0天";,而不是期望的";0年10个月0天";。你能解释一下原因吗?
显然,问题源于我的默认时区(我不知道为什么(,它是欧洲时区。如果我把时区改为美国,例如
date_default_timezone_set('America/Los_Angeles');
解决了问题
即使我更改时区,对于二月有28天的年份和diff360("2010-01-30","2010-03-01"(这样的情况,上述代码也会输出$totaldays=1,这是不正确的。我写了下面的代码,它不依赖于php的日期函数,为任何感兴趣的人模拟excel的DAYS360函数,
//inputs 2 dates yyyy-mm-dd (start,finish) outputs total diff days+1
public function Diff360($arxi, $telos) {
//i consider all months to have 30 days
if(substr($arxi,8,2) == 31){
$arxi = substr($arxi,0,8) . "30";
}
if(substr($telos,8,2) == 31){
$telos = substr($telos,0,8) . "30";
}
$arxi_d = explode("-",$arxi);
$telos_d = explode("-",$telos);
$totaldays = 0;
if( $telos_d[0] == $arxi_d[0] ){
if($telos_d[1] == $arxi_d[1]){
return $telos_d[2] - $arxi_d[2] + 1;
}
$totaldays += 30 - $arxi_d[2] + 1;
$yp_minas = $arxi_d[1] + 1;
$totaldays += ($telos_d[1] - $yp_minas) *30;
$totaldays += $telos_d[2];
return $totaldays;
}
if( $telos_d[0] - $arxi_d[0] > 1 ){
$totaldays += 360 * ( $telos_d[0] - $arxi_d[0] - 1 );
}
$totaldays += 30 - $arxi_d[2] + 1;
$yp_minas = $arxi_d[1] + 1;
if( $yp_minas <= 12 ){
$totaldays += ( 13 - $yp_minas ) * 30;
}
$totaldays += ($telos_d[1] - 1) * 30;
$totaldays += $telos_d[2];
return $totaldays;
}