php中360天/年,30天/月格式的两个日期之间的差异

问题描述 投票:0回答:3

我想问一个关于这篇文章中给出的答案的问题(如何获取 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
    );
}

除了某些情况(例如,

diff360("2020-09-01", "2021-07-01");
,它输出“0 年,9 个月,0 天”,而不是所需的“0 年,10 个月,0 天”。 能解释一下原因吗?

php date datetime diff
3个回答
1
投票

显然问题源于我的默认时区(我不知道为什么),即欧洲。如果我将时区更改为美国,例如

date_default_timezone_set('America/Los_Angeles');

问题解决了


0
投票

即使我更改时区,对于二月有 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;
  }

© www.soinside.com 2019 - 2024. All rights reserved.