Do not use '[+/-]{n} month' to get the last day of the month.
If you use '+1 month' on the first of the month, it sets the date to the next first of the month. This behaviour gives the impression, that php considers the length of a month, which is not true.
Basically if you use '+1 month' it takes the month number, adds 1 and parses result as a new date. But if you use '+1 month' on the last day of a month, the result is unexpected as 2009-05-31 becomes 2009-06-31 which is an invalid date and then interpreted as 2009-07-01.
DateTime::modify
(PHP 5 >= 5.2.0)
DateTime::modify — Alters the timestamp
Beschreibung
Alter the timestamp of a DateTime object by incrementing or decrementing in a format accepted by strtotime().
Parameter-Liste
- object
-
Nur bei prozeduralem Aufruf: Ein von date_create() zurückgegebens DateTime Objekt.
- modify
-
String in a relative format accepted by strtotime().
Rückgabewerte
Returns the modified DateTime.
Beispiele
Beispiel #1 A date_modify() example
<?php
$date = new DateTime("2006-12-12");
$date->modify("+1 day");
echo $date->format("Y-m-d");
?>
Das oben gezeigte Beispiel erzeugt folgende Ausgabe:
2006-12-13
Siehe auch
- strtotime() - Wandelt ein beliebiges in englischer Textform angegebenes Datum in einen UNIX-Zeitstempel (Timestamp) um
DateTime::modify
tacker at php dot net
03-Jul-2009 10:18
03-Jul-2009 10:18
tom at r dot je
18-Jun-2009 02:43
18-Jun-2009 02:43
If you want to find the next working day (assuming mon-fri) you can use this:
<?php
$d = new DateTime();
$day = $d->format('w');
if ($day == 0 || $day >= 5) $d->modify('+' . ((7-$day+1) % 7) . ' days');
else $d->modify('+1 day');
?>
Cas Adriani
15-Jun-2009 10:51
15-Jun-2009 10:51
I couldn't find a function to skip to the begin of a week or end of a week so I found an easy way to do so. Hopefully it's helpful to others.
<?php
$d = new DateTime();
//Set object to begin (Monday) of the week
$d->modify( "-" . ( $d->format("N") - 1 ) . ' days' );
echo $d->format("m-d");
//Set object to end (Sunday) of the week
$d->modify( "+" . ( 7 - $d->format("N") ) . ' days' );
echo $d->format("m-d");
?>
Anodyne
31-Mar-2009 04:04
31-Mar-2009 04:04
As far as I can tell, the documentation for date_modify seems to be inconsistent with the functionality exhibited in PHP 5.2.9 (and perhaps other versions)
I was trying to figure out why a call to date_modify was returning null in PHP 5.2.9. An older version of the documentation for date_modify at http://php.chinaunix.net/manual/zh/function.date-modify.php (for PHP 5 >= 5.1.0) explains that date_modify returns NULL on success, or FALSE on failure.
I suspect the new version of date_modify returns a DateTime object instead of null or false:
PRESUMABLY NEW:
DateTime date_modify ( DateTime $object , string $modify )
OLD:
null/boolean date_modify ( DateTime $object , string $modify )
