[英]How to get the difference between two dates with 360 days/year, 30 days/month format?
[英]Difference between two dates with 360 days/year, 30 days/month format in php
我想问一个关于这篇文章中给出的答案的问题( How to get the difference between two dates with 360 days/year, 30 days/month format? )我不能发表评论,因为我没有必要的声誉. 提供的function
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
);
}
通常效果很好,但某些情况除外,例如diff360("2020-09-01", "2021-07-01");
它输出“0 年,9 个月,0 天”,而不是所需的“0 年,10 个月,0 天”。 你能解释一下为什么吗?
我测试了 diff360("2020-09-01", "2021-07-01"),它给了我“0 年,10 个月,0 天”。
显然问题出在我的默认时区(我不知道为什么)是欧洲。 如果我将时区更改为美国,例如
date_default_timezone_set('America/Los_Angeles');
问题已经解决了
即使我更改时区,对于 2 月有 28 天情况的年份,如 diff360("2010-01-30","2010-03-01"),上面的代码输出 $totaldays = 1,这是不正确的。 我写了下面的代码,它不依赖于 php 的日期函数,为任何感兴趣的人模拟 excel 的 DAYS360 function,
//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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.