首页 文章

php DateTime diff - 包括范围内的两个日期?

提问于
浏览
1

我一直在使用DateTime Diff(在php中)获取日期对的各种设置 - 要显示的两个格式化日期,从日期到现在的差异(例如“开始日期是3个月2天前”),以及之间的长度两个日期(“长度为2个月3天”) .

问题是DateTime Diff忽略其中一天,所以如果开始是昨天而结束是明天,则它给出2天,而我想要3,因为两个日期都应该包含在长度中 . 如果只是几天,我可以简单地在结果中添加1,但我想使用Diff的年/月/日结果,这些结果是在构造中确定的 .

我发现获得所需结果的唯一方法是为开始和结束创建一个DateTime(以获取格式化的日期和差异) . 然后结束DateTime,添加1天,然后计算出长度 .

它有点笨拙,但似乎没有办法告诉DateTime Diff在结果中包含开始日期和结束日期 .

1 回答

  • 1

    DateTime封装了特定的时刻 . "yesterday"不是时刻而是时间范围 . "tomorrow"也一样 .

    DateTime::diff()不会忽视任何事情;它只是为您提供两个时刻之间的确切差异(白天,小时,分钟a.s.o.) .

    如果你想得到“明天”和“昨天”之间的差异为“3天”你可以减去“昨天”的第一秒(在“明天”的最后一秒之后的一秒) .

    像这样:

    // Always set the timezone of your DateTime objects to avoid troubles
    $tz = new DateTimeZone('Europe/Bucharest');
    // Some random time yesterday
    $date1 = new DateTime('2016-07-08 21:30:15', $tz);
    // Other random time tomorrow
    $date2 = new DateTime('2016-07-10 12:34:56', $tz);
    
    // Don't mess with $date1 and $date2;
    // clone them and do whatever you want with the clones
    $yesterday = clone $date1;
    $yesterday->setTime(0, 0, 0);         // first second of yesterday (the midnight)
    $tomorrow = clone $date2;
    $tomorrow->setTime(23, 59, 59)               // last second of tomorrow
             ->add(new DateInterval('PT1S'));    // one second
    
    // Get the difference; it is the number of days between and including $date1 and $date2
    $diff = $tomorrow->diff($yesterday);
    
    printf("There are %d days between %s and %s (including the start and end date).\n",
         $diff->days, $date1->format('Y-m-d'), $date2->format('Y-m-d')
    );
    

相关问题