2

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.

Austin
  • 127
  • 1
  • 8
  • Possible duplicate of [Finding the number of days between two dates](https://stackoverflow.com/questions/2040560/finding-the-number-of-days-between-two-dates) – rollstuhlfahrer Jan 23 '18 at 23:06

3 Answers3

4

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.

Devon Bessemer
  • 34,461
  • 9
  • 69
  • 95
  • I agree that using Carbon is the best choice, especially because it is built into Laravel. If you are using a datetime field other than the timestamps, you must declare the field(s) in the protected $dates array on the model in order for them to be converted to Carbon objects. – parker_codes Jan 23 '18 at 23:19
2

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');
rollstuhlfahrer
  • 3,988
  • 9
  • 25
  • 38
0

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');

Danes
  • 86
  • 8