PHP 8.1.28 Released!

DateTime::modify

date_modify

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

DateTime::modify -- date_modifyAltera la marca temporal

Descripción

Estilo orientado a objetos

public DateTime::modify(string $modify): DateTime

Estilo por procedimientos

date_modify(DateTime $object, string $modify): DateTime

Altera la marca temporal de un objeto DateTime aumentando o disminuyendo en un formato aceptado por strtotime().

Parámetros

object

Solamente para el estilo por procedimientos: Un objeto DateTime devuelto por date_create(). La función modifica este objeto.

modify

Una cadena de fecha/hora. Los formatos válidos se explican en Formatos de fecha y hora.

Valores devueltos

Devuelve el objeto DateTime para la cadena de métodos o false en caso de error.

Historial de cambios

Versión Descripción
5.3.6 Las sentencias de fecha/hora absolutas ahora toman efecto. Anteriormente, sólo se utilizaban las partes relativas.
5.3.0Se ha cambiado el valor devuelto en caso de éxito de null a DateTime.

Ejemplos

Ejemplo #1 Ejemplo de DateTime::modify()

Estilo orientado a objetos

<?php
$fecha
= new DateTime('2006-12-12');
$fecha->modify('+1 day');
echo
$fecha->format('Y-m-d');
?>

Estilo por procedimientos

<?php
$fecha
= date_create('2006-12-12');
date_modify($fecha, '+1 day');
echo
date_format($fecha, 'Y-m-d');
?>

El resultado de los ejemplos sería:

2006-12-13

Ejemplo #2 Cuidado al añadir o sustraer meses

<?php
$fecha
= new DateTime('2000-12-31');

$fecha->modify('+1 month');
echo
$fecha->format('Y-m-d') . "\n";

$fecha->modify('+1 month');
echo
$fecha->format('Y-m-d') . "\n";
?>

El resultado del ejemplo sería:

2001-01-31
2001-03-03

Ver también

add a note

User Contributed Notes 1 note

up
0
php_net at striderweb dot com
7 hours ago
You have to be a bit careful with variables here. If for example you want to add a variable amount of minutes you might use `->modify("+$min"). This will not work out if `$min` is a negative number, because modify will see the "+" and ignore the "-". If `$min` equals -10, modify in this example will add ten minutes, not subtract!

What is happening is if the modify string has two operations, the first will be obeyed and later ones will be ignored.

So "+-10 minutes" will add ten minutes, even though you might expect it to add the negative number. Similarly "--10 minutes" will subtract ten minutes, despite the apparent logic of subtracting a negative number.
To Top