Domanda

Come aggiungo un certo numero di giorni alla data corrente in PHP?

Ho già ricevuto la data corrente con:

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

Devo solo aggiungere x numero di giorni

È stato utile?

Soluzione

php supporta le funzioni di data in stile c. Puoi aggiungere o sottrarre periodi di date con frasi in stile inglese tramite la funzione strtotime . Esempi di ...

$Today=date('y:m:d');

// add 3 days to date
$NewDate=Date('y:m:d', strtotime("+3 days"));

// subtract 3 days from date
$NewDate=Date('y:m:d', strtotime("-3 days"));

// PHP returns last sunday's date
$NewDate=Date('y:m:d', strtotime("Last Sunday"));

// One week from last sunday
$NewDate=Date('y:m:d', strtotime("+7 days Last Sunday"));

o

<select id="date_list" class="form-control" style="width:100%;">
<?php
$max_dates = 15;
$countDates = 0;
while ($countDates < $max_dates) {
    $NewDate=Date('F d, Y', strtotime("+".$countDates." days"));
    echo "<option>" . $NewDate . "</option>";
    $countDates += 1;
}
?>

Altri suggerimenti

un giorno è 86400 secondi.

$tomorrow = date('y:m:d', time() + 86400);

Il modo più semplice per aggiungere x no. di giorni ..

echo date('Y-m-d',strtotime("+1 day"));    //+1 day from today

OPPURE dalla data specificata ...

echo date('Y-m-d',strtotime("+1 day", strtotime('2007-02-28')));

Il date_add () La funzione dovrebbe fare quello che vuoi. Inoltre, consulta i documenti (non ufficiali, ma quelli ufficiali sono un po 'sparsi) per il DateTime , è molto più bello lavorare con le funzioni procedurali in PHP.

Con php 5.3

    $date = new DateTime();
    $interval = new DateInterval('P1D');
    echo $date->format('Y-m-d') , PHP_EOL;
    $date->add($interval);
    echo $date->format('Y-m-d'), PHP_EOL;
    $date->add($interval);
    echo $date->format('Y-m-d'), PHP_EOL;

verrà emesso

2012/12/24

2012/12/25

2012/12/26

Se hai bisogno di questo codice in più punti, ti suggerisco di aggiungere una breve funzione per mantenere il codice più semplice e più facile da testare.

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

Quindi puoi usarlo ovunque in questo modo:

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

Aggiungi 15 giorni a un elemento selezionato (usando il suggerimento " Alive to Die ")

<select id="date_list" class="form-control" style="width:100%;">
<?php
$max_dates = 15;
$countDates = 0;
while ($countDates < $max_dates) {
    $NewDate=Date('F d, Y', strtotime("+".$countDates." days"));
    echo "<option>" . $NewDate . "</option>";
    $countDates += 1;
}
?>

$NewDate=Date('Y-m-d', strtotime("+365 days"));
  

echo $ NewDate; // 2020/5/21

$ NewTime = mktime (date ('G'), date ('i'), date ('s'), date ('n'), date ('j') + $ DaysToAdd, date ( 'Y'));

Da documentazione mktime :

  

mktime () è utile per eseguire l'aritmetica e la convalida della data, poiché calcolerà automaticamente il valore corretto per l'input fuori intervallo.

Il vantaggio di questo metodo è che puoi aggiungere o sottrarre qualsiasi intervallo di tempo (ore, minuti, secondi, giorni, mesi o anni) in una riga di codice di facile lettura.

Attenzione, c'è un compromesso in termini di prestazioni, poiché questo codice è circa 2,5 volte più lento dello strtotime (" +1 giorno ") a causa di tutte le chiamate alla funzione date (). Considera di riutilizzare questi valori se sei in un ciclo.

<?php
$dt = new DateTime;
if(isset(<*>GET['year']) && isset(<*>GET['week'])) {
    $dt->setISODate(<*>GET['year'], <*>GET['week']);
} else {
    $dt->setISODate($dt->format('o'), $dt->format('W'));
}
$year = $dt->format('o');
$week = $dt->format('W');
?>

<a href="<?php echo <*>SERVER['PHP_SELF'].'?week='.($week-1).'&year='.$year; ?>">Pre Week</a> 
<a href="<?php echo <*>SERVER['PHP_SELF'].'?week='.($week+1).'&year='.$year; ?>">Next Week</a>
<table width="100%" style="height: 75px; border: 1px solid #00A2FF;">
<tr>
<td style="display: table-cell;
    vertical-align: middle;
    cursor: pointer;
    width: 75px;
    height: 75px;
    border: 4px solid #00A2FF;
    border-radius: 50%;">Employee</td>
<?php
do {
    echo "<td>" . $dt->format('M') . "<br>" . $dt->format('d M Y') . "</td>\n";
    $dt->modify('+1 day');
} while ($week == $dt->format('W'));
?>
</tr>
</table>
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top