The theoretical limits of the date range seem to be "-9999-01-01" through "9999-12-31" (PHP 5.2.9 on Windows Vista 64):
<?php
$d = new DateTime("9999-12-31");
$d->format("Y-m-d"); // "9999-12-31"
$d = new DateTime("0000-12-31");
$d->format("Y-m-d"); // "0000-12-31"
$d = new DateTime("-9999-12-31");
$d->format("Y-m-d"); // "-9999-12-31"
?>
Dates above 10000 and below -10000 do not throw errors but produce weird results:
<?php
$d = new DateTime("10019-01-01");
$d->format("Y-m-d"); // "2009-01-01"
$d = new DateTime("10009-01-01");
$d->format("Y-m-d"); // "2009-01-01"
$d = new DateTime("-10019-01-01");
$d->format("Y-m-d"); // "2009-01-01"
?>
DateTime::__construct
date_create
(PHP 5 >= 5.2.0)
DateTime::__construct -- date_create — Devuelve un nuevo objeto DateTime
Descripción
Estilo orientado a objetos
Estilo por procedimientos
Devuelve un nuevo objeto DateTime.
Parámetros
-
time -
Una cadena de fecha/hora. Los formatos válidos son explicados en Formatos de fecha y hora.
Introduzca
NULLaquí para obtener el instante actual cuando se use el parámetro$timezone. -
timezone -
Un objeto DateTimeZone que representa la zona horaria de
$time.Si se omite
$timezone, se usará la zona horaria actual.Nota:
El parámetro
$timezoney la zona horaria actuales se ignoran cuando el parámetro$timees una fecha UNIX (p.ej. @946684800) o especifica una zona horaria (p.ej. 2010-01-28T15:00:00+02:00).
Valores devueltos
Devuelve una nueva instancia de DateTime.
Estilo por procedimientos devuelve FALSE en caso de error.
Errores/Excepciones
Emite una Exception en caso de error.
Historial de cambios
| Versión | Descripción |
|---|---|
| 5.3.0 | Si se especifica una fecha no válida, ahora se lanza una excepción. Anteriormente se emitía un error. |
Ejemplos
Ejemplo #1 Ejemplo de DateTime::__construct()
Estilo orientado a objetos
<?php
try {
$fecha = new DateTime('2000-01-01');
} catch (Exception $e) {
echo $e->getMessage();
exit(1);
}
echo $fecha->format('Y-m-d');
?>
Estilo por procedimientos
<?php
$fecha = date_create('2000-01-01');
if (!$fecha) {
$e = date_get_last_errors();
foreach ($e['errors'] as $error) {
echo "$error\n";
}
exit(1);
}
echo date_format($fecha, 'Y-m-d');
?>
El resultado de los ejemplos serían:
2000-01-01
Ejemplo #2 Complejidades de DateTime::__construct()
<?php
// Fecha/hora especificadas en la zona horaria de su ordenador.
$fecha = new DateTime('2000-01-01');
echo $fecha->format('Y-m-d H:i:sP') . "\n";
// Fecha/hora especificadas en la zona horaria especificada.
$fecha = new DateTime('2000-01-01', new DateTimeZone('Pacific/Nauru'));
echo $fecha->format('Y-m-d H:i:sP') . "\n";
// Fecha/hora actuales en la zona horaria de su ordenador.
$fecha = new DateTime();
echo $fecha->format('Y-m-d H:i:sP') . "\n";
// Fecha/hora actuales en la zona horaria especificada.
$fecha = new DateTime(null, new DateTimeZone('Pacific/Nauru'));
echo $fecha->format('Y-m-d H:i:sP') . "\n";
// Usar una fecha UNIX. Observe que el resultado está en la zona horaria UTC.
$fecha = new DateTime('@946684800');
echo $fecha->format('Y-m-d H:i:sP') . "\n";
// Desbordamiento de valores no existentes.
$fecha = new DateTime('2000-02-30');
echo $fecha->format('Y-m-d H:i:sP') . "\n";
?>
El resultado del ejemplo sería algo similar a:
2000-01-01 00:00:00-05:00 2000-01-01 00:00:00+12:00 2010-04-24 10:24:16-04:00 2010-04-25 02:24:16+12:00 2000-01-01 00:00:00+00:00 2000-03-01 00:00:00-05:00
Ver también
- DateTime::createFromFormat() - Devuelve un nuevo objeto DateTime formateado según el formato especificado
- DateTimeZone::__construct() - Crea un nuevo objeto DateTimeZone
- Formatos de Fecha y Hora
- Configuración ini de date.timezone
- date_default_timezone_set() - Establece la zona horaria predeterminada usada por todas las funciones de fecha/hora en un script
- DateTime::getLastErrors() - Devuelve las advertencias y los errores
- checkdate() - Validar una fecha gregoriana
A definite "gotcha" (while documented) that exists in the __construct is that it ignores your timezone if the $time is a timestamp. While this may not make sense, the object does provide you with methods to work around it.
<?php
// New Timezone Object
$timezone = new DateTimeZone('America/New_York');
// New DateTime Object
$date = new DateTime('@1306123200', $timezone);
// You would expect the date to be 2011-05-23 00:00:00
// But it actually outputs 2011-05-23 04:00:00
echo $date->format('Y-m-d H:i:s');
// You can still set the timezone though like so...
$date->setTimezone($timezone);
// This will now output 2011-05-23 00:00:00
echo $date->format('Y-m-d H:i:s');
?>
There's a reason for ignoring the time zone when you pass a timestamp to __construct. That is, UNIX timestamps are by definition based on UTC. @1234567890 represents the same date/time regardless of time zone. So there's no need for a time zone at all.
Also forgot to mention, that MySQL "zeroed" dates do not throw an error but produce a non-sensical date:
<?php
$d = new DateTime("0000-00-00");
$d->format("Y-m-d"); // "-0001-11-30"
?>
Another good reason to write your own class that extends from DateTime.
"The $timezone parameter and the current timezone are ignored when the $time parameter […] is a UNIX timestamp."
Watch out – this means that these two are NOT equivalent, they result in different timezones (unless your current timezone is GMT):
<?php
$d = new DateTime(); $d->setTimestamp($t);
echo $o->format('O');
// +0200
$d = new DateTime('@' . $t);
echo $o->format('O');
// +0000
?>
Note that although a milliseconds portion in ISO8601 timestamps is legal, PHP cannot parse them and will throw an exception. No parser in PHP can parse it.
