drno94939847 2012-02-23 15:57 采纳率: 0%
浏览 19
已采纳

PHP DateTime差异奇怪的结果

I am having a weird problem with PHP's DateTime diff method. I've been using DateTime methods for some while now and thought I've got the hang of it, but this problem amazes me.

I am using the diff method to determine the number of months/days between two dates. Today, I used the following code:

$start = new DateTime('2012-03-01');
$end = new DateTime('2012-03-31');

$period = $start->diff($end);

var_dump($period);

Which produced the following output:

object(DateInterval)[3]
  public 'y' => int 0
  public 'm' => int 1 // Shouldn't this be 0?
  public 'd' => int 1 // And where does this come from? Would expect 30.
  public 'h' => int 0
  public 'i' => int 0
  public 's' => int 0
  public 'invert' => int 0
  public 'days' => int 30

As my comment above says, where the hell does the 1m1d come from (I would expect 0m30d). I can't for the life of me figure out where it gets this value from. I also tried putting the midnight timestamp 00:00:00 behind both dates to make sure it wasn't a time thing, but that made no difference to the output.

Can anybody explain this outcome to me? This problem occurs on my Debian development server, running PHP 5.3.3 with Xdebug 2.1.1 and Suhosin 0.9.32.1 installation.

Update

Reproduced this problem on my production server, which is on CentOS 6.0 with "raw" PHP 5.3.8 without any extensions/patches.

Update 2

I managed to find a "workaround" (only working at this moment in time). If I change the absolute dates to:

$start = new DateTime('first day of next month');
$end = new DateTime('last day of next month');

It does give 0m30d as output. Still, I'm stumped by the above, so if anyone has a clue about that, please let me know!

  • 写回答

3条回答 默认 最新

  • douweibiao8471 2012-02-23 17:04
    关注

    Congratulations, you have just discovered DST! If you check with the DST switchover for your timezone, you will see that $start is actually getting Feb-29, and $end getting Mar-30. (2-3) = 1 (therefore, m=1), and (29-30) = 1 (therefore, d=1).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来