doupuzhimuhan9216 2016-02-23 02:27
浏览 18
已采纳

计算2个日期之间的差异我做错了什么?

I'm trying to calculate the difference between 2 dates: $now and $old to get -> how long as past since old datetime.

$current_date = time();
$old= new DateTime($dateTimeString);
$now= new DateTime($current_date);
$interval = $now->diff($old);

I was trying with these values: 2016-02-23 02:15:43 --- 2016-02-22 21:45:11 and the result was more than 14hours of difference. I print the result like this:

$interval->format('%i Hours ago.');
$interval->format('%d Days ago.');

What I am doing wrong please?

  • 写回答

1条回答 默认 最新

  • douchao1957 2016-02-23 13:57
    关注

    The problem is here:

    $current_date = time();
    $now = new DateTime($current_date);
    

    The value returned by time() is the number of seconds since 1970-01-01 00:00:00 UTC. The DateTime constructor tries to interpret it as a date that uses one of the usual date formats, it fails and produces a DateTime objects initialized with 0 (i.e. 1970-01-01 00:00:00 UTC).

    If you want to create a new DateTime object from an Unix timestamp (the value returned by time() you can use DateTime::createFromFormat()

    $current_time = time();
    $now = DateTime::createFromFormat('U', $current_time);
    

    Or you can pass the timestamp prefixed with '@' to DateTime::__construct():

    $current_time = time();
    $now = new DateTime('@'.$current_time);
    

    This format is explained in the Compound date/time formats page.

    But the easiest way to create a DateTime object that contains the current date and time is to either pass 'now' as argument to the constructor or omit it altogether:

    $now1 = new DateTime('now');
    $now2 = new DateTime();
    

    The two DateTime objects constructed above should be identical (there is a small chance they are 1-second apart, though) and they both must contain the current date & time.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?