I want to get a reminding day left using timestamp and current date. Was wondering if I can do a simple subtraction using those.
How do I calculate the currentdate -timestamp?
PHP's timestamps are identical to a Unix timestamp - seconds since Jan 1 1970. So yeah, a simple subtraction will give you a time difference in seconds, which you can convert to days by diving by 86,400 (seconds in a day):
$days = (time() - $oldtimestamp) / 86400;
Try this:
// Will return the number of days between the two dates passed in
function count_days( $a, $b )
{
// First we need to break these dates into their constituent parts:
$gd_a = getdate( $a );
$gd_b = getdate( $b );
// Now recreate these timestamps, based upon noon on each day
// The specific time doesn't matter but it must be the same each day
$a_new = mktime( 12, 0, 0, $gd_a['mon'], $gd_a['mday'], $gd_a['year'] );
$b_new = mktime( 12, 0, 0, $gd_b['mon'], $gd_b['mday'], $gd_b['year'] );
// Subtract these two numbers and divide by the number of seconds in a
// day. Round the result since crossing over a daylight savings time
// barrier will cause this time to be off by an hour or two.
return round( abs( $a_new - $b_new ) / 86400 );
}
There is also the, preferred, option of using the DateTime
and DateInterval
classes.
$now = new DateTime;
$then = new DateTime;
$then->setTimestamp($timestamp);
$diff = $now->diff($then);
echo $diff->days;
The above will also make available the number of years, months, days, etc. should those be of interest to you (as well as the total number of days as shown).