简体   繁体   中英

How do I use current date to minus timestamp to get reminding days?

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的时间戳与Unix时间戳相同-自1970年1月1日以来为秒。是的,简单的减法将为您提供时差,以秒为单位,您可以通过乘以86,400(一天的秒数)来转换为天:

$days = (time() - $oldtimestamp) / 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).

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 ); 
} 

Answer courtesy of the Doc

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM