PHP Velho Oeste 2024

strtotime

(PHP 4, PHP 5, PHP 7, PHP 8)

strtotimeConvierte una descripción de fecha/hora textual en Inglés a una fecha Unix

Descripción

strtotime(string $time, int $now = time()): int

Esta función espera que se proporcione una cadena que contenga un formato de fecha en Inglés US e intentará convertir ese formato a una fecha Unix (el número de segundos desde el 1 de Enero del 1970 00:00:00 UTC), relativa a la marca de tiempo dada en now, o la marca de tiempo actual si now no se proporciona.

Cada parámetro de esta función utiliza la zona horaria predeterminada a menos que se especifique una en ese parámetro. Se ha de tener cuidado de no usar diferentes zonas horarias en cada parámetro a menos que sea esa la intención. Véase la función date_default_timezone_get() para las diferentes maneras de definir la zona horaria predeterminada.

Parámetros

time

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

now

La marca de tiempo que se usa como base para el cálculo de las fechas relativas.

Valores devueltos

Devuelve una marca de tiempo si se tuvo éxito, false si no. Antes de PHP 5.1.0, esta funcion devolvía -1 si fallaba.

Errores/Excepciones

Cada vez que se llame a una función de fecha/hora se generará un E_NOTICE si la zona horaria no es válida, y/o un mensaje E_STRICT o E_WARNING si se emplea la configuración del sistema o la variable global TZ. Véase también date_default_timezone_set()

Historial de cambios

Versión Descripción
5.3.0 Antes de PHP 5.3.0, formatos de tiempo relativo que se suministran al parámetro time de la función strtotime() como this week, previous week, last week, y next week se interpreta como un período de 7 días en relación con la fecha y hora actual, en lugar de un período de semana de Monday a Sunday.
5.3.0 Antes de PHP 5.3.0, 24:00 no era un formato válido y strtotime() devolvía false.
5.2.7 En PHP 5 anterior a 5.2.7, las peticiones de una incidencia de un día de la semana dado en un mes donde ese día de la semana era el primer día del mes, añadía incorrectamente una semana a la marca de tiempo devuelta. Esto ha sido corregido en 5.2.7 y versiones posteriores.
5.1.0 Ahora devuelve false si falla, en vez de -1.
5.1.0

Ahora muestra un error E_STRICT y E_NOTICE cuando ocurren errores con zonas horarias.

5.0.2 En PHP 5 hasta 5.0.2, "now" y otros momentos relativos son computados erróneamente como la medianoche de hoy. Esto difiere de otras versiones donde es computado como el momento actual.
5.0.0 Los microsegundos comenzaron a estar permitidos, pero son ignorados.

Ejemplos

Ejemplo #1 Un ejemplo de strtotime()

<?php
echo strtotime("now"), "\n";
echo
strtotime("10 September 2000"), "\n";
echo
strtotime("+1 day"), "\n";
echo
strtotime("+1 week"), "\n";
echo
strtotime("+1 week 2 days 4 hours 2 seconds"), "\n";
echo
strtotime("next Thursday"), "\n";
echo
strtotime("last Monday"), "\n";
?>

Ejemplo #2 Comprobar si falla

<?php
$cadena
= 'No Válida';

// antes de PHP 5.1.0 se debería de comparar con -1, en vez de con false
if (($timestamp = strtotime($cadena)) === false) {
echo
"La cadena ($cadena) es falsa";
} else {
echo
"$cadena == " . date('l dS \o\f F Y h:i:s A', $timestamp);
}
?>

Notas

Nota:

Si el número del año se especifica en un formato de dos dígitos, los valores entre 00-69 hacen referencia a 2000-2069 y 70-99 a 1970-1999. Vea las notas de abajo para las posibles diferencias en sistemas de 32 bit (las fechas posibles podrían terminar en 2038-01-19 03:14:07).

Nota:

El rango válido de una marca de tiempo es típicamente desde Fri, 13 Dec 1901 20:45:54 UTC a Tue, 19 Jan 2038 03:14:07 UTC. (Estas son las fechas que se corresponden con los valores máximo y mínimo de un entero con signo de 32 bit.)

Antes de PHP 5.1.0, no todas las plataformas admitían marcas de tiempo negativas, por lo que el rango de fechas puede estar limitado a no anteriores a la época Unix. Esto significa que, p.ej., las fechas anteriores al 1 de enero de 1970 no funcionarán en Windows, en algunas distribuciones de Linux, y en otros pocos sistemas operativos.

Para PHP versión 64-bit, el rángo válido de fechas es en la práctica infinito, ya que 64 bits pueden representar aproximadamente 293.000 millones de años en cualquier dirección.

Nota:

Las fechas en los formatos m/d/y o d-m-y no son ambiguas al observar el separador entre los distintos componentes: si el separador es una barra (/), se asume el formato norteamericano m/d/y; mientras que si el separador es un guion (-) o un punto (.), se asume el formato europeo d-m-y. Si, sin embargo, el año se proporciona en un formato de dos dígitos y el separador es un guion (-), la cadena de la fecha se analiza como y-m-d.

Para evitar esta ambigüedad potencial es mejor usar fechas ISO 8601 (YYYY-MM-DD) o DateTime::createFromFormat() cuando sea posible.

Nota:

No es aconsejable utililzar esta función para operaciones matemáticas. Es mejor usar los métodos DateTime::add() y DateTime::sub() de PHP 5.3 y posterior, o el método DateTime::modify() de PHP 5.2.

Ver también

add a note add a note

User Contributed Notes 4 notes

up
10
cesarfrisa at yahoo dot es
10 months ago
This is the link to the relative formats that can be used in this function. It's not easy to find in the documentation.

https://www.php.net/manual/en/datetime.formats.relative.php

Here some examples:
<?php
$today
= date( 'Y-m-d', strtotime( 'today' ) );
echo
"Today: " . $today;

// Print: Today: 2023-06-01

//Basic Example
$tomorrow = date( 'Y-m-d', strtotime( 'tomorrow' ) );
echo
"\n\nTomorrow: " . $tomorrow;

// Print: Tomorrow: 2023-06-02

$yesterday = date( 'Y-m-d', strtotime( 'yesterday' ) );
echo
"\n\nYesterday: " . $yesterday;

// Print: Yesterday: 2023-05-31

// Add o subtract Month
$variable = date( 'Y-m-d', strtotime( '+1 month' ) );
echo
"\n\nAdd one month: " . $variable;

// Print: Add one month: 2023-07-01

$variable = date( 'Y-m-d', strtotime( '-1 month' ) );
echo
"\n\nSubstract one month: " . $variable;

// Print: Substract one month: 2023-05-01

// More complex formats:
// ERROR / BUG: If today is the last day of the month. This examples can be one error or bug.
// If you are looking el first day of previous or next month you dont must use last Relative Format.
// You must use 'first day of 2 months ago' or 'first day of previous month'
// See you:
// https://bugs.php.net/bug.php?id=22486
// https://bugs.php.net/bug.php?id=44073
// strtotime("+1 Month")
// produces the wrong result on the 31st day of the month.
// on January 31, date("m",strtotime("+1 Month")) will return 03 instead of 02

// Another example:
$dt1 = strtotime("2023-01-30");
$month = strtotime("+1 month", $dt1);
echo
"\n\nToday is: " . date( 'Y-m-d', $dt1 );
echo 
"\nBUG add month: " . date("Y-m-d", $month);

// Print:
// Today is: 2023-01-30
// BUG add month: 2023-03-02

$dt1 = strtotime("2023-02-28");
$month = strtotime("-1 month", $dt1);
echo
"\n\nToday is: " . date( 'Y-m-d', $dt1 );
echo 
"\nBUG substract month: " . date("Y-m-d", $month);

// Print:
// Today is: 2023-02-28
// BUG substract month: 2023-01-28

$dt1 = strtotime("2023-01-30");
$month = strtotime("first day of next month", $dt1);
echo
"\n\nToday is: " . date( 'Y-m-d', $dt1 );
echo 
"\nFirst day of next month: " . date("Y-m-d", $month);

// Print:
// Today is: 2023-01-30
// First day of next month: 2023-02-01

$dt1 = strtotime("2023-02-28");
$month = strtotime("last day of last month", $dt1);
echo
"\n\nToday is: " . date( 'Y-m-d', $dt1 );
echo 
"\nLast day of last month: " . date("Y-m-d", $month);

// Print:
// Today is: 2023-02-28
// Last day of last month: 2023-01-31

$dt1 = strtotime("2023-02-28");
$month = strtotime("first day of 2 months ago", $dt1);
echo
"\n\nToday is: " . date( 'Y-m-d', $dt1 );
echo 
"\nFirst day of 2 months ago: " . date("Y-m-d", $month);

// Print:
// Today is: 2023-02-28
// First day of 2 months ago: 2022-12-01

?>
up
7
info at pipasjourney dot com
10 months ago
Be aware of this: 1 month before the 31st day, it will return the same month:

<?php
echo date('m', strtotime('2023-05-30 -1 month')) ; //returns 04
echo date('m', strtotime('2023-05-31 -1 month')) ; //returns 05, not 04
?>

So, don't use this to operate on the month of the result.
A better way to know what month was the previous month would be:

<?php
//considering today is 2023-05-31...

$firstOfThisMonth = date('Y-m') . '-01'; //returns 2023-05-01
echo date('m', strtotime($firstOfThisMonth . ' -1 month')) ; //returns 04
?>
up
8
Vyacheslav Belchuk
1 year ago
Be careful when using two numbers as the year. I came across this situation:

<?php

echo strtotime('24.11.22');
echo
date('d.m.Y H:i:s', 1669324282)  .  "\n\n";

// But
echo strtotime('24.11.2022');
echo
date('d.m.Y H:i:s', 1669237200);

?>

Output:

1669324282
25.11.2022 00:11:22

1669237200
24.11.2022 00:00:00
up
-5
MarkAgius at markagius dot co dot uk
11 months ago
Note:
If day of month is 12 or less, or year is entered as a two digit number and less than 31 or 12 then you may get the wrong time value.
If you know the format used with the date string, then use the following code: (PHP version 5.5 or later)
[code]
function getStrtotime($timeDateStr, $formatOfStr="j/m/Y"){
  // Same as strtotime() but using the format $formatOfStr.
  // Works with PHP version 5.5 and later.
  // On error reading the time string, returns a date that never existed. 3/09/1752 Julian/Gregorian calendar switch.
  $timeStamp = DateTimeImmutable::createFromFormat($formatOfStr,$timeDateStr);
  if($timeStamp===false){
    // Bad date string or format string.
    return -6858133619; // 3/09/1752
  } else {
    // Date string and format ok.
    return $timeStamp->format("U"); // UNIX timestamp from 1/01/1970,  0:00:00 gmt
  }
}

print date("j/m/Y", getStrtotime("1/02/2022", "j/m/Y"))." Standard format. (j)<BR>\n";
print date("j/m/Y", getStrtotime("1/02/2022", "d/m/Y"))." Standard format. (d)<BR>\n";
print date("j/m/Y", getStrtotime("1/02/2022", "j/m/y"))." Standard format. (y) &lt;-- Bad date as 2022 is not two digits.<BR>\n";
print date("j/m/Y", getStrtotime("21/02/2022", "j/m/Y"))." Standard format. (j)<BR>\n";
print date("j/m/Y", getStrtotime("21/02/2022", "d/m/Y"))." Standard format. (d)<BR>\n";
print date("j/m/Y", getStrtotime("2/01/2022", "m/j/Y"))." US format.<BR>\n";
print date("j/m/Y", getStrtotime("2-01-22", "m-j-y"))." Two digit year, US format. (Y)<BR>\n";
print date("j/m/Y", getStrtotime("2-01-22", "m-j-Y"))." Two digit year, US format. (y) &lt;-- Wrong year if two digits.<BR>\n";
print date("j/m/Y", getStrtotime("3/09/1752", "j/m/Y"))." No such date.<BR>\n";
print date("j/m/Y", getStrtotime("50/00/19999", "j/m/Y"))." Bad date string.<BR>\n";
print date("j/m/Y", getStrtotime("1-02-2022", "j/m/Y"))." Wrong - or / used.<BR>\n";
[/code]
Output:
1/02/2022 Standard format. (j)
1/02/2022 Standard format. (d)
3/09/1752 Standard format. (y) <-- Bad date as 2022 is not two digits.
21/02/2022 Standard format. (j)
21/02/2022 Standard format. (d)
1/02/2022 US format.
1/02/2022 Two digit year, US format. (Y)
1/02/0022 Two digit year, US format. (y) <-- Wrong year if two digits.
3/09/1752 No such date.
3/09/1752 Bad date string.
3/09/1752 Wrong - or / used.
To Top