PHP DateInterval
La clase de PHP DateInterval representa un intervalo de fechas.
Sinopsis / Synopsis
class DateInterval {
/* Properties */
public int $y;
public int $m;
public int $d;
public int $h;
public int $i;
public int $s;
public float $f;
public int $invert;
public mixed $days;
public bool $from_string;
public string $date_string;
/* Methods */
public __construct(string $duration)
public static createFromDateString(string $datetime): DateInterval|false
public format(string $format): string
}
Propiedades
https://blastcoding.com/php-dateinterval/#propiedades$y – Número de años.
$m – Número de meses.
$d – Cantidad de días.
$h – Cantidad de horas.
$i – Minutos.
$s – Segundos.
$f – Microsegundos, 1000000 microsegundos es 1 segundo
$invert – es 1 si el intervalo representa un periodo de tiempo negativo, en caso de no serlo su valor será 0.
$days – Si el objeto DateInterval fue creado por DateTimeImmutable::diff() o DateTime::diff(), entonces este es el número total de días completos entre las fechas de inicio y fin. De lo contrario, $days será false.
$from_string – Si el objeto DateInterval fue creado por DateInterval::createFromDateString(), entonces el valor de esta propiedad será true, y la propiedad $date_string será poblada. De lo contrario, el valor será false y las propiedades $y, $m, $d, $h, $i, $s, $f, $invert y $days serán pobladas.
$date_string – The string used as argument to DateInterval::createFromDateString().
$one_year = new DateInterval('P1Y');
$one_year_ago = new DateTime();
$one_year_ago->sub($one_year);
echo $one_year_ago->format("d-m-Y");
echo "\n".$one_year->y;
echo "\n".$one_year->m;
echo "\n".$one_year->d;
26-04-2022 years: 1 months:0 days: 0
Métodos
__construct
https://blastcoding.com/php-dateinterval/#__constructCrea un nuevo objeto DateInterval
Sinopsis / Synopsispublic DateInterval::__construct(string $duration)Sintaxis / Sintax
$dinterval = new DateInterval($duration);
$duration – debe ser un string que representa un formato el cual debe empezar con P(period) seguido de un valor entero y alguno de los siguientes valores en la tabla:
| Period Designator | Description |
|---|---|
| Y | years |
| M | months |
| D | days |
| W | weeks. Converted into days. Prior to PHP 8.0.0, can not be combined with D. |
| H | hours |
| M | minutes |
| S | seconds |
Tenga en cuenta que el valor del string $duration debe ser un formato admitido, no puede ser "" o no pasarle nada.
$one_year = new DateInterval('P1Y');
$one_year_ago = new DateTime();
$one_year_ago->sub($one_year);
echo $one_year_ago->format("d-m-Y");
- ‘P1Y1D’ ✔
- ‘P1D1M’ ✘
- ‘P1Y2M’ ✔
- ‘P1Y5M1H’ ✔
- ‘P1Y1W1D’ ✘
createFromDateString
https://blastcoding.com/php-dateinterval/#createFromDateStringConfigura un DateInterval a partir de las partes relativas de la cadena
Retorna un nuevo objeto DateInterval si tiene éxito, false en caso de fallo.
public static DateInterval::createFromDateString(string $datetime): DateInterval|falseSintaxis / Sintax
$dinterval = DateInterval::createFromDateString('2 weeks');
en el string podras usar:
- year/s
- month/s
- week/s
- day/s
- second/s
- + en caso de tener que sumar valor
- – en caso de restar otro valor
- ‘first’ | ‘second’ | ‘third’ | ‘fourth’ | ‘fifth’ | ‘sixth’ | ‘seventh’ | ‘eighth’ | ‘ninth’ | ‘tenth’ | ‘eleventh’ | ‘twelfth’ | ‘next’ | ‘last’ | ‘previous’ | ‘this’
format
https://blastcoding.com/php-dateinterval/#formatDa formato al intervalo de tiempo
Sinopsis / Synopsispublic DateInterval::format(string $format): string
| format character | Description | Example values |
|---|---|---|
| % | Literal % | % |
| Y | Years, numeric, at least 2 digits with leading 0 | 01, 03 |
| y | Years, numeric | 1, 3 |
| M | Months, numeric, at least 2 digits with leading 0 | 01, 03, 12 |
| m | Months, numeric | 1, 3, 12 |
| D | Days, numeric, at least 2 digits with leading 0 | 01, 03, 31 |
| d | Days, numeric | 1, 3, 31 |
| a | Total number of days as a result of a DateTime::diff() or (unknown) otherwise |
4, 18, 8123 |
| H | Hours, numeric, at least 2 digits with leading 0 | 01, 03, 23 |
| h | Hours, numeric | 1, 3, 23 |
| I | Minutes, numeric, at least 2 digits with leading 0 | 01, 03, 59 |
| i | Minutes, numeric | 1, 3, 59 |
| S | Seconds, numeric, at least 2 digits with leading 0 | 01, 03, 57 |
| s | Seconds, numeric | 1, 3, 57 |
| F | Microseconds, numeric, at least 6 digits with leading 0 | 007701, 052738, 428291 |
| f | Microseconds, numeric | 7701, 52738, 428291 |
| R | Sign «–» when negative, «+» when positive | –, + |
| r | Sign «–» when negative, empty when positive | –, |
A continuación un ejemplo bastante completo de como usar los caracteres:
Format interval
$interval = new DateInterval('P1Y2M3DT4H5M6S');
echo $interval->format('La duración es de %r%y años, %m meses, %d días, %h horas, %i minutos y %s segundos.');
La duración es de 1 años, 2 meses, 3 días, 4 horas, 5 minutos y 6 segundos.

