Forum Moderators: coopster

Message Too Old, No Replies

Calculate number of days between two dates

         

usrbin

1:24 am on Feb 3, 2017 (gmt 0)

5+ Year Member Top Contributors Of The Month



I'm creating two dates and comparing the number of days between them. My script works great but I feel like I'm converting an object several times before its in a usable format. I'm wondering if there is a less awkward way to do it.

// I'm supplied with a timestamp that I create a reference date
$date1 = date_create_from_format('U', 376358400);

// I'm trying to find the next Saturday after a provided date
$date2= strtotime('next Saturday', strtotime('01 FEB 2017'));

// Step one of calculating the number of days apart
$days = date_diff($date1, new DateTime("@$date2"));

// Step two of calculating the number of days apart
$distance = $days->format('%R%a');

phranque

7:54 am on Feb 3, 2017 (gmt 0)

WebmasterWorld Administrator 10+ Year Member Top Contributors Of The Month



//calculate the number of days apart and format the time difference
$distance = date_diff($date1, new DateTime("@$date2"))->format('%R%a');

usrbin

11:01 am on Feb 3, 2017 (gmt 0)

5+ Year Member Top Contributors Of The Month



Thank you!

What about when I create "new DateTime" using the data from $date2? Could I do something to $date2 where it's already in whatever format needed for the date_diff without having to create a new DateTime?

And what about $date1? If I already have the unix epoch seconds, can I use this in a more direct method?

// I'm supplied with a timestamp that I create a reference date
$date1 = date_create_from_format('U', 376358400);

// I'm trying to find the next Saturday after a provided date
$date2= strtotime('next Saturday', strtotime('01 FEB 2017'));

// Calculate number of days apart
$distance = date_diff($date1, new DateTime("@$date2"))->format('%R%a');

phranque

11:34 am on Feb 3, 2017 (gmt 0)

WebmasterWorld Administrator 10+ Year Member Top Contributors Of The Month



you could do it all in one line but it still does about the same amount of work and your code becomes less readable.