Thursday, March 8, 2012

Counting Days Difference using PHP

Sorry for not righting in here lately, not use to doing this, so here is something that I have learned this week. Have you ever wanted to find out how many days it has been between two days, well her is a way using PHP. I'll show the code I did, then I'll explain it.

$days = (strtotime($today) - strtotime($olderdate)) / (60 * 60 * 24);

Basically what has to happen is that you convert your dates to seconds with strtotime( ). Then subtract the two dates to get the difference between the two dates. The back half is 60 seconds times 60 minutes times 24 hours. That is 86400 seconds. So take your difference in dates and then divide that by the 86400 or 60 * 60 * 24. Now sometimes if the date has some information indicating time, and you only what to show days, then before you output, you will need to format to only show the number of days by encapsulate $days with number_format($days). This will only show the days without rounding the number.

I hope you enjoyed this little tid bit, thanks for reading.

No comments:

Post a Comment