Increase days to php current Date()

前端 未结 11 1296
予麋鹿
予麋鹿 2020-12-04 19:13

How do I add a certain number of days to the current date in PHP?

I already got the current date with:

$today = date(\'y:m:d\');

Ju

11条回答
  •  时光取名叫无心
    2020-12-04 19:35

    If you need this code in several places then I'd suggest that you add a short function to keep your code simpler and easier to test.

    function add_days( $days, $from_date = null ) {
        if ( is_numeric( $from_date ) ) { 
            $new_date = $from_date; 
        } else { 
            $new_date = time();
        }
    
        // Timestamp is the number of seconds since an event in the past
        // To increate the value by one day we have to add 86400 seconds to the value
        // 86400 = 24h * 60m * 60s
        $new_date += $days * 86400;
    
        return $new_date;
    }
    

    Then you can use it anywhere like this:

    $today       = add_days( 0 );
    $tomorrow    = add_days( 1 );
    $yesterday   = add_days( -1 );
    $in_36_hours = add_days( 1.5 );
    
    $first_reminder  = add_days( 10 );
    $second_reminder = add_days( 5, $first_reminder );
    $last_reminder   = add_days( 3, $second_reminder );
    

提交回复
热议问题