[英]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.