Welcome to WebmasterWorld Guest from 54.205.126.164

Forum Moderators: coopster & jatar k

Calculate number of days between two dates

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

New User

Top Contributors Of The Month

joined:Aug 21, 2016
posts:12
votes: 0


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');
7:54 am on Feb 3, 2017 (gmt 0)

Administrator

WebmasterWorld Administrator phranque is a WebmasterWorld Top Contributor of All Time 10+ Year Member Top Contributors Of The Month

joined:Aug 10, 2004
posts:10763
votes: 45


//calculate the number of days apart and format the time difference
$distance = date_diff($date1, new DateTime("@$date2"))->format('%R%a');
11:01 am on Feb 3, 2017 (gmt 0)

New User

Top Contributors Of The Month

joined:Aug 21, 2016
posts:12
votes: 0


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');
11:34 am on Feb 3, 2017 (gmt 0)

Administrator

WebmasterWorld Administrator phranque is a WebmasterWorld Top Contributor of All Time 10+ Year Member Top Contributors Of The Month

joined:Aug 10, 2004
posts:10763
votes: 45


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

Join The Conversation

Moderators and Top Contributors

Hot Threads This Week

Featured Threads

Free SEO Tools

Hire Expert Members