dragonsun2005
2018-01-23 23:05
浏览 896
已采纳

查找两个日期对象之间的天数

I currently have two date objects like this:

2018-01-17 22:50:30 2018-01-23 23:04:36

And I am trying to find the number of days between them. What is the proper way to do this in Laravel/PHP? Is just subtracting them sufficient?

I tried the possible solution linked below and it has not been working for me.

图片转代码服务由CSDN问答提供 功能建议

我目前有两个这样的日期对象:

2018 -01-17 22:50:30 2018-01-23 23:04:36

我正试图找到 它们之间的天数。 在Laravel / PHP中执行此操作的正确方法是什么? 只是减去它们就足够了吗?

我尝试了下面链接的可能解决方案但它并没有为我工作。

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • dslk6326846 2018-01-23 23:10
    已采纳

    Since this is tagged Laravel, you have access to Carbon which makes this easy:

    Assuming both are Carbon instances:

    $date1->diffInDays($date2);
    

    Eloquent timestamps are automatically converted to Carbon instances for manipulation.

    打赏 评论
  • dongxiz5342 2018-01-23 23:10

    If you have 2 timestamps as string or unix epoch, you can just substract them and divide by 1 day in seconds: Source

    $now = time(); // or your date as well
    $your_date = strtotime("2010-01-01");
    $datediff = $now - $your_date;
    
    echo round($datediff / (60 * 60 * 24));
    

    If you are using DateTime objects: Source

    $datetime1 = new DateTime('2009-10-11');
    $datetime2 = new DateTime('2009-10-13');
    $interval = $datetime1->diff($datetime2);
    echo $interval->format('%R%a days');
    
    打赏 评论
  • dqeonr8554 2018-01-23 23:11

    Solution

    $datetime1 = new DateTime('2018-01-17 22:50:30'); $datetime2 = new DateTime('2018-01-23 23:04:36'); $interval = $datetime1->diff($datetime2); echo $interval->format('%R%a days');

    打赏 评论

相关推荐 更多相似问题