PHP 8.3.4 Released!

La clase DateInterval

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

Introducción

Representa un intervalo de fechas.

Un intervalo de fechas almacena o bien una cantidad fija de instantes (en años, meses, días, horas, etc.) o bien una cadena con un instante relativo en el formato que admite el constructor de DateTime.

Sinopsis de la Clase

class DateInterval {
/* Propiedades */
public integer $y;
public integer $m;
public integer $d;
public integer $h;
public integer $i;
public integer $s;
public mixed $days;
/* Métodos */
public __construct(string $interval_spec)
public format(string $format): string
}

Propiedades

y

Número de años.

m

Número de meses.

d

Número de días.

h

Número de horas.

i

Número de minutos.

s

Número de segundos.

invert

Es 1 si el intervalo representa un periodo de tiempo negativo y 0 si no. Véase DateInterval::format().

days

Si el objeto DateInterval se creó con DateTime::diff(), entonces es el número total de días entre las fechas de inicio y fin. Si no, days será false.

Antes de PHP 5.4.20/5.5.4, en lugar de false se recibía -99999 al acceder a la propiedad.

Tabla de contenidos

add a note

User Contributed Notes 3 notes

up
34
cb
1 year ago
If you want to reverse a date interval use array_reverse and iterator_to_array. I've found using invert to be unreliable.

<?php
$start_date
= date_create("2021-01-01");
$end_date = date_create("2021-01-05"); // If you want to include this date, add 1 day

$interval = DateInterval::createFromDateString('1 day');
$daterange = new DatePeriod($start_date, $interval ,$end_date);

function
show_dates ($dr) {
foreach(
$dr as $date1){
echo
$date1->format('Y-m-d').'<br>';
}
}

show_dates ($daterange);

echo
'<br>';

// reverse the array

$daterange = array_reverse(iterator_to_array($daterange));

show_dates ($daterange);

?>

Gives
2021-01-01
2021-01-02
2021-01-03
2021-01-04

2021-01-04
2021-01-03
2021-01-02
2021-01-01
up
2
julio dot necronomicon at gmail dot com
2 months ago
More simple example i use to add or subtract.

<?php
$Datetime
= new Datetime('NOW', new DateTimeZone('America/Bahia'));
$Datetime->add(DateInterval::createFromDateString('2 day'));

echo
$Datetime->format("Y-m-d H:i:s");
?>
up
-1
nateb at gurutechnologies dot net
3 years ago
Many people have commented on doing a reverse interval on a date time. I personally find a backwards year to be a little strange to think about and instead opt to work with just intervals. This is the easiest I have found.

<?php
$one_year
= new DateInterval('P1Y');
$one_year_ago = new DateTime();
$one_year_ago->sub($one_year);
?>

Instead of:

<?php
$one_year_ago
= new DateInterval( "P1Y" );
$one_year_ago->invert = 1;
$one_year_ago = new DateTime();
$one_year_ago->add($one_year);
?>
To Top