I'm trying to work with dates for the first time, I did it something about that with Flash but it's different.
I have two different dates and I'd like to see the difference in hours and days with them, I've found too many examples but not what I'm loking for:
<?php
$now_date = strtotime (date ('Y-m-d H:i:s')); // the current date
$key_date = strtotime (date ("2009-11-21 14:08:42"));
print date ($now_date - $key_date);
// it returns an integer like 5813, 5814, 5815, etc... (I presume they are seconds)
?>
How can I convert it to hours or to days?
The
DateTime
diff function returns aDateInterval
object. This object consists of variabeles related to the difference. You can query the days, hours, minutes, seconds just like in the example above.Example:
See the manual about
DateTime
.Sadly, it's a PHP 5.3> only feature.
TheGrandWazoo mentioned a method for php 5.3>. For lower versions you can devide the number of seconds between the two dates with the number of seconds in a day to find the number of days.
For days, you do:
If you want to know how many hours are still left, you can use the modulo operator (%)
If you dont have PHP5.3 you could use this method from userland (taken from WebDeveloper.com)
Well, you can always use date_diff, but that is only for PHP 5.3.0+
The alternative would be math.
There are 60 seconds per minute, which means there are 3600 seconds per hour.
And, of course, if you need days ...
I prefer to use epoch/unix time deltas. Time represented in seconds and as such you can very quickly divide by 3600 for hours and divide by 24*3600=86400 for days.