Formatos de fecha y hora admitidos

Tabla de contenidos

Esta sección describe todos los formatos diferentes que entiende el analizador de strtotime(), de DateTime y de date_create(). Los formatos están agrupados por secciones. En la mayoría de los casos, se pueden emplear los formatos de secciones diferentes en la misma cadena de fecha/hora. Se proporcionan ejemplos para cada uno de los formatos admitidos, así como una descripción del formato. En los formatos, los caracteres entre comillas simples son insensibles a mayúsculas-minúsculas, ('t' podría ser t o T), y los caracteres entre comillas dobles son sensibles a mayúsculas-minúsculas ("T" es solamente T).

add a note

User Contributed Notes 2 notes

up
2
Anonymous
1 month ago
The year-only format is a potential issue that could cause problems for you.

<?php
echo (new DateTime('1994'))->format('Y-m-d');
// Outputs today's date in the year 1984, e.g. "1994-08-15"
echo (new DateTime('2004'))->format('Y-m-d');
// Outputs today's date in the *current* year, e.g. "2024-08-15"
?>

This is because, as noted above in the documentation, 2004 gets interpreted as a time, e.g. 20:04, rather than as a year. Even though 1994 is interpreted as a year.

One solution is to add ' T' to the end of the string:

<?php
echo (new DateTime('1994 T'))->format('Y-m-d');
// "1994-08-15"
echo (new DateTime('2004 T'))->format('Y-m-d');
// "2004-08-15"
?>

Another would be to add an arbitrary time to the beginning of the string:

<?php
echo (new DateTime('11:00 1994'))->format('Y-m-d');
// "1994-08-15"
echo (new DateTime('11:00 2004'))->format('Y-m-d');
// "2004-08-15"
?>
up
1
Anonymous
13 days ago
I wrote previously that appending a 'T' to a year forces PHP to interpret the date as a year rather than a time. This does not appear to be universally true. While this method did work for me in my previous development environment (PHP 8.1 on Ubuntu 20.04), it does not work after upgrading my development environment (PHP 8.3 on Ubuntu 24.04). The 'T' is instead seen as a timezone.

Further testing shows that PHP 8.1 (and even earlier PHP versions) also have this new behavior I am observing. Therefore, I can only assume the behavior is dependent on environment and/or build rather than PHP version.

The suggestion about adding an actual time string to the year, e.g. '00:00 2004', is still valid. This appears to be the only reliable way to force PHP to interpret a string as a date rather than a datetime.
To Top