Questo articolo mostra come confrontare due date in PHP.
1. Utilizzo strtotime()
funzione
Una soluzione semplice è convertire entrambe le date in timestamp Unix e confrontare i timestamp per determinare l'ordine delle date. Puoi usare il strtotime() funzione per analizzare una stringa contenente un formato di data inglese in un timestamp Unix, che può quindi essere confrontato utilizzando operatori di confronto.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<?php $first = strtotime("2017-12-25"); $second = strtotime("2018-10-12"); if ($first < $second) { echo "First date is less than the second date"; } else if ($first > $second) { echo "First date is more than the second date"; } else { echo "First date is same as the second date"; } ?> |
Se le tue date sono sempre nel formato data inglese ('YYYY-MM-DD'
), è possibile eseguire semplici confronti di stringhe per determinare se la prima data è minore, maggiore o uguale alla seconda data.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<?php $first = "2017-12-25"; $second = "2018-10-12"; if ($first < $second) { echo "First date is less than the second date"; } else if ($first > $second) { echo "First date is more than the second date"; } else { echo "First date is same as the second date"; } ?> |
2. Utilizzo DateTime
class
In alternativa, potresti usare il DateTime class per eseguire un confronto tra due date. Il vantaggio dell'utilizzo di questo metodo è che può analizzare qualsiasi stringa di data e ora nel formato specificato. L'esempio seguente mostra come è possibile confrontare due DateTime
oggetti che utilizzano operatori di confronto:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<?php $first = DateTime::createFromFormat("d-m-Y", "25-12-2017"); $second = DateTime::createFromFormat("d-m-Y", "12-10-2018"); if ($first < $second) { echo "First date is less than the second date"; } else if ($first > $second) { echo "First date is more than the second date"; } else { echo "First date is same as the second date"; } ?> |
Per trovare la differenza di data e ora tra due date, puoi utilizzare il file DateTime::diff() funzione. Dal momento che restituisce il file DateInterval
oggetto, utilizzare il DateInterval::format() funzione con l'opzione di formattazione '%R%a'
per ottenere il numero di giorni.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<?php $first = DateTime::createFromFormat("d-m-Y", "25-12-2017"); $second = DateTime::createFromFormat("d-m-Y", "12-10-2018"); $interval = $first->diff($second); echo "Difference: " . $interval->format('%R%a days'), PHP_EOL; $sign = $interval->format('%R'); $days = $interval->format('%a'); if ($days === "0") { echo "First date is same as the second date"; } else if ($sign === "+") { echo "First date is less than the second date"; } else if ($sign === "-") { echo "First date is more than the second date"; } ?> |
Questo è tutto ciò che serve per confrontare due date in PHP.