PHP : Date difference in days

Tue, Jun 17, 2008

PHP

You might need to calculate the date difference in days using PHP. You can easily calculate the days difference by using something like the code below.

The code shown above takes the UNIX timestamp of two dates and subtracts the older date from the newer date to get the number of seconds. Then we simply divide the seconds by 60 (since there are 60 seconds in a minute) to get the minutes, again by 60 (since there are 60 minutes in an hour) to get the hours and lastly by 24 (since there are 24 hours in a day) to get the number of days.

You don’t have to subtract the newer date from the older date though since we’re making use of the php abs() function which will automatically return an absolute value and eliminate a minus sign to make a negative value positive.

I hope that helps!

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • E-mail this story to a friend!
  • LinkedIn
  • Live
  • Ping.fm
  • StumbleUpon
  • Print this article!
  • Reddit
  • TwitThis
, , , , , , , , ,
scriptlancebannerpng

This post was written by:

Antonie Potgieter - who has written 52 posts on Lost-In-Code.

I (Antonie Potgieter) am a software engineer/web developer located in South Africa. My full-time work is the management of Tribulant Software and the development of its software packages.

Contact the author

13 Comments For This Post

  1. Kavita Says:

    Really helpful!!!!!!!!!

  2. Iain Says:

    Indeed.

    I was working on an old site that only had version 4.0 of MySQL installed so no DATEDIFF command.

    Your code above allowed me to do the calculation almost as easily in PHP.

  3. lolyz Says:

    ohh dear..itz so easy…just tell me how to get end date from starting date and number of days + time , and also eliminate the weekends..

  4. Jirka Fornous Says:

    This technique is daylight saving proof, because the one hour is everytime rounded correctly.

  5. seth odhiambo Says:

    how can i create a form that store data that is fed on it to the database and can calculate the date from which a customer logs in for booking in a hotel and on the day when he/she checks out it automatically calculates the days spent and amount to be paid and declares the room vacant

  6. Hedda Says:

    Can you show the code for the calculation of the date difference? Thank you.

  7. Moni Says:

    where is the code?

  8. luglio7 Says:

    where the hell is the coooode ? :)

  9. tast Says:

    where is the code plssssssssssss

  10. xQmail Says:

    uhm, I don’t see any code…?!

  11. Laatste Nieuws Says:

    Good thinking, this is way easier then the calculation in PHP itself…

  12. sunil Says:

    reeeeeeeeeee there no code

  13. sunil Says:

    conde is not there

Leave a Reply