PHP 8.1.9 Released!

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

User Contributed Notes 19 notes

up
122
kumar AT swatantra.info Swatantra Kumar
9 years ago
The "+1 month" issue with strtotime
===================================
As noted in several blogs, strtotime() solves the "+1 month" ("next month") issue on days that do not exist in the subsequent month differently than other implementations like for example MySQL.

<?php
echo date( "Y-m-d", strtotime( "2009-01-31 +1 month" ) ); // PHP:  2009-03-03
echo date( "Y-m-d", strtotime( "2009-01-31 +2 month" ) ); // PHP:  2009-03-31
?>

<?php
SELECT DATE_ADD
( '2009-01-31', INTERVAL 1 MONTH ); // MySQL:  2009-02-28
?>
up
49
cristinawithout
10 years ago
WARNING when using "next month", "last month", "+1 month",  "-1 month" or any combination of +/-X months. It will give non-intuitive results on Jan 30th and 31st.

As described at : http://derickrethans.nl/obtaining-the-next-month-in-php.html

<?php
$d
= new DateTime( '2010-01-31' );
$d->modify( 'next month' );
echo
$d->format( 'F' ), "\n";
?>

In the above, using "next month" on January 31 will output "March" even though you might want it to output "February". ("+1 month" will give the same result. "last month", "-1 month" are similarly affected, but the results would be seen at beginning of March.)

The way to get what people would generally be looking for when they say "next month" even on Jan 30 and Jan 31 is to use "first day of next month":

<?php
$d
= new DateTime( '2010-01-08' );
$d->modify( 'first day of next month' );
echo
$d->format( 'F' ), "\n";
?>

<?php
$d
= new DateTime( '2010-01-08' );
$d->modify( 'first day of +1 month' );
echo
$d->format( 'F' ), "\n";
?>
up
16
joe at strtotime dot co dot uk
7 years ago
A useful testing tool for strtotime() and unix timestamp conversion:
http://strtotime.co.uk/
up
19
michal dot kocarek at brainbox dot cz
13 years ago
strtotime() also returns time by year and weeknumber. (I use PHP 5.2.8, PHP 4 does not support it.) Queries can be in two forms:
- "yyyyWww", where yyyy is 4-digit year, W is literal and ww is 2-digit weeknumber. Returns timestamp for first day of week (for me Monday)
- "yyyy-Www-d", where yyyy is 4-digit year, W is literal, ww is 2-digit weeknumber and dd is day of week (1 for Monday, 7 for Sunday)

<?php
// Get timestamp of 32nd week in 2009.
strtotime('2009W32'); // returns timestamp for Mon, 03 Aug 2009 00:00:00
// Weeknumbers < 10 must be padded with zero:
strtotime('2009W01'); // returns timestamp for Mon, 29 Dec 2008 00:00:00
// strtotime('2009W1'); // error! returns false

// See timestamp for Tuesday in 5th week of 2008
strtotime('2008-W05-2'); // returns timestamp for Tue, 29 Jan 2008 00:00:00
?>

Weeknumbers are (probably) computed according to ISO-8601 specification, so doing date('W') on given timestamps should return passed weeknumber.
up
7
mirco dot babin at gmail dot com
3 years ago
One important thing you should remember is that the timestamp value returned by time() is time-zone agnostic and gets the number of seconds since 1 January 1970 at 00:00:00 UTC. This means that at a particular point in time, this function will return the same value in the US, Europe, India, Japan, ...

strtotime() will convert a string WITHOUT a timezone indication as if the string is a time in the default timezone ( date_default_timezone_set() ). So converting a UTC time like '2018-12-06T09:04:55' with strtotime() actually yields a wrong result. In this case use:

<?php
function UTCdatestringToTime($utcdatestring)
{
   
$tz = date_default_timezone_get();
   
date_default_timezone_set('UTC');

   
$result = strtotime($utcdatestring);

   
date_default_timezone_set($tz);
    return
$result;
}
?>

Test:
<?php
$tz
= 'Europe/Amsterdam';
$utctime = '2018-12-06T09:04:55';

if (!
date_default_timezone_set($tz)) {
   
WriteLine('Setting default timezone to ' . $tz . ' failed');
    die;
}

WriteLine();
WriteLine('Default timezone set to ' . $tz);
WriteLine('UTC time: ' . $utctime);
WriteLine();

WriteLine('[ UTCdatestringToTime ]');
$phptime = UTCdatestringToTime($utctime);
WriteLine('PHP time: ' . $phptime);
WriteTime($phptime, true);
WriteTime($phptime, false);
WriteLine();

WriteLine('-------------------------------------------------------------------------------');
WriteLine('[ strtotime($utctime) - Converts $utctime as if it was in timezone ' . $tz . ' because the string has no timezone specification ]');
$phptime = strtotime($utctime); //Seconds since the unix epoch
WriteLine('PHP time: ' . $phptime);
WriteTime($phptime, true);
WriteTime($phptime, false);

function
WriteLine($text = '')
{
    echo
$text . "\r\n";
}

function
WriteTime($time, bool $asUTC)
{
   
$tz = date_default_timezone_get();
    if (
$asUTC) date_default_timezone_set('UTC');
   
   
WriteLine('--> (' . date_default_timezone_get() . ') ' . date('Y-m-d H:i:s', $time));
   
    if (
$asUTC) date_default_timezone_set($tz);
}
?>

Test output:
<?php

Default timezone set to Europe/Amsterdam
UTC time
: 2018-12-06T09:04:55

[ UTCdatestringToTime ]
PHP time: 1544087095
--> (UTC) 2018-12-06 09:04:55
--> (Europe/Amsterdam) 2018-12-06 10:04:55

-------------------------------------------------------------------------------
[
strtotime($utctime) - Converts $utctime as if it was in timezone Europe/Amsterdam because the string has no timezone specification ]
PHP time: 1544083495
--> (UTC) 2018-12-06 08:04:55
--> (Europe/Amsterdam) 2018-12-06 09:04:55
*/
?>
up
6
Steve GS
5 years ago
The difference between 'today' and 'now' is the former strips off the time (setting it to 00:00, ie. midnight just past), and the latter includes the time - assuming UTC unless specified otherwise.

I run a theatre's website.  Obviously, I need to ensure shows that have already happened do not appear on web pages, so I use something on the lines of:

    $listIt = (strtotime($end_date) >= strtotime('today') ? 1 : 0);

where $end_date is the final date in a show series.  So if tonight's show is the last, it will stay on the web page until 00:00 tomorrow.

I don't normally include performance times in the date field because some shows have matinées, others don't - so I use a free-form performance time field in the CMS instead (where even 'Time: TBD' is allowed).  [The only instance where I DO include the time is when there are two different shows on the same day, to ensure they appear in chronological order.]

So strtotime($end_date) will always return the timestamp at 00:00 that day.  If I instead used:

    $listIt = (strtotime($end_date) >= strtotime('now') ? 1 : 0);

the function would return $listIt = 0 at all times today - something I don't want.

HTH
up
10
shannon
4 years ago
I tried using sams most popular example but got incorrect results.

Incorrect:
<?php
echo date("jS F, Y", strtotime("11.12.10"));
// outputs 10th December, 2011

echo date("jS F, Y", strtotime("11/12/10"));
// outputs 12th November, 2010

echo date("jS F, Y", strtotime("11-12-10"));
// outputs 11th December, 2010 
?>

Then I read the notes which said:
if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed. ***If, however, the year is given in a two digit format and the separator is a dash (-), the date string is parsed as y-m-d.***

Therefore, the above code does not work on 2 digit years - only 4 digit years
up
10
me at will morgan dot co dot you kay
9 years ago
For negative UNIX timestamps, strtotime seems to return the literal you passed in, or it may try to deduct the number of seconds from today's date.

To work around this behaviour, it appears that the same behaviour as described in the DateTime classes applies:

http://php.net/manual/en/datetime.construct.php

Specifically this line here (in the EN manual):

> The $timezone parameter and the current timezone are ignored when the $time parameter either is a UNIX timestamp (e.g. @946684800) or specifies a timezone (e.g. 2010-01-28T15:00:00+02:00).

Therefore strtotime('@-1000') returns 1000 seconds before the epoch.

Hope this helps.
up
2
marlonsouza90 at hotmail dot com
2 years ago
strtotime();

exemplo strtotime(date("Y-m-d") . "+1month");

A strtotime também funciona quando concatenamos strings,
up
4
chris at teamsiems dot com
12 years ago
It took me a while to notice that strtotime starts searching from just after midnight of the first day of the month. So, if the month starts on the day you search for, the first day of the search is actually the next occurrence of the day.

In my case, when I look for first Tuesday of the current month, I need to include a check to see if the month starts on a Tuesday.

<?php
if (date("l", strtotime("$thisMonth $thisYear"))=='Tuesday') {
  echo
"<p>This month starts on a Tuesday. Use \"$thisMonth $thisYear\" to check for first Tuesday.</p>\n";
} else {
  echo
"<p>This month does not start on a Tuesday. Use \"first tuesday $thisMonth $thisYear\" to check for first Tuesday.</p>\n";
}
?>
up
5
kyle at frozenonline dot com
18 years ago
I was having trouble parsing Apache log files that consisted of a time entry (denoted by %t for Apache configuration). An example Apache-date looks like: [21/Dec/2003:00:52:39 -0500]

Apache claims this to be a 'standard english format' time. strtotime() feels otherwise.

I came up with this function to assist in parsing this peculiar format.

<?php
function from_apachedate($date)
{
        list(
$d, $M, $y, $h, $m, $s, $z) = sscanf($date, "[%2d/%3s/%4d:%2d:%2d:%2d %5s]");
        return
strtotime("$d $M $y $h:$m:$s $z");
}
?>

Hope it helps anyone else seeking such a conversion.
up
3
Michael Muryn (MickoZ)
10 years ago
[red.: This is a bug, and should be fixed. I have file an issue]

This comment apply to PHP5+

We can now do thing like this with strtotime:
<?php
$weekMondayTime
= strtotime('Monday this week');
?>
However this works based on a week starting Sunday.  I do not know if we can tweak this PHP behavior, anyone know?

If you want the timestamp of the start of the ISO Week (i.e. on Monday) as defined by ISO 8601, you can use this one liner:
<?php
$isoWeekStartTime
= strtotime(date('o-\\WW')); // {isoYear}-W{isoWeekNumber}
?>

You can also find out the start of week of any time and format it into an ISO date with another one liner like this:
<?php
$isoWeekStartDate
= date('Y-m-d', strtotime(date('o-\\WW', $time)));
?>

For more information about ISO-8601 and ISO week date:
http://en.wikipedia.org/wiki/ISO_8601#Week_dates
http://en.wikipedia.org/wiki/ISO_week_date
up
1
a dot fruchi at bit-runners dot com
11 years ago
If you want to confront a date stored into mysql as a date field (not a datetime) and a date specified by a literal string, be sure to add "midnight" to the literal string, otherwise they won't match:

<?php
//I.E.: today is 17/02/2011

echo strtotime('2011-01-01'); //1293836400
echo strtotime('first day of last month'); //1293888128 Note: it's different from the previous one, since it computes also the seconds passed from midnight!!! So this one is always greater than simple '2011-01-01'
echo strtotime('midnight first day of last monty');//1293836400 Note: it's the same as '2011-01-01'

?>
up
0
Black Hat Rocker
1 year ago
*The case 30/11/-0001*
With the following note, I will report a particular behaviour of function strtotime() I want to call it «The case 30/11/-0001».  It is very common and known but never reported  here. Passing the input parameter '0000-00-00' to the function it returns a wrong and not supported timestamp value. It can be seen with these statement

<?php echo date('d/m/Y', strtotime('0000-00-00')); // returns 30/11/-0001  ?>

It seems there's no way to avoid that, but it is possibile to do workaround with if/3operator clausole simply as follow

<?php strcmp($date "0000-00-00")? date('d/m/Y', strtotime($date) ) :  date('d/m/Y') ?>

Otherwise a simple way is to avoid to store to the DB the value '0000-00-00' and insert a default data value (i.e. with the mySQL function NOW() which sets the date on today's date)
up
-2
phpmanual at NOSPAM dot headbank dot co dot uk
2 months ago
For those still using php versions < 8.0.0, it may help to know that explicitly supplying the 2nd argument $baseTime as NULL does *not* have the same effect as omitting it.

<?php
function adjustedTime($adjustment, $baseTime = null) {
  echo
date('Y-m-d H:i:s', strtotime($adjustment, $baseTime));
}

adjustTime('+1 day');

//1970-01-02 01:00:00
?>
Supplying NULL is equivalent to supplying int(0).

So if you wrap strtotime() in this manner with a nullable $baseTime, make sure in your code to inspect $baseTime and supply time() instead of NULL, or call strtotime() without it in that case.
up
0
vlad dot savitsky at gmail dot com
4 years ago
Little bit unexpected behaviour for me. Small integers treats like time.
strtotime(0) => false,
strtotime(1) => false,
strtotime(12) => false,
strtotime(123) => false,
strtotime(1234) => 1528194840, //Time '12:34'
strtotime(12345) => false,
strtotime(123456) => 1528194896, // Time '12:34:56'
strtotime(1234567) => false,
strtotime(12345678) => false,
strtotime(123456789) => false,
up
-1
marcodemaio at vanylla dot it
11 years ago
NOTE: strtotime returns different values when the Week day does not match the date.

Simple example:

<?php
$d1
= strtotime("26 Oct 0010 12:00:00 +0100");
$d2 = strtotime("Tue, 26 Oct 0010 12:00:00 +0100");
$d3 = strtotime("Sun, 26 Oct 0010 12:00:00 +0100"); //But Oct 26 is a Tuesday, NOT a Sunday.

echo $d1; //ok 1288090800 that is "26 Ott 2010 - 11:00";
echo $d2; //ok 1288090800 that is "26 Ott 2010 - 11:00";
echo $d3; //WRONG! 1288522800 that is "31 Ott 2010 - 11:00";
?>

Sometime I found RSS feeds that contains week days that do not match the date.

A possible solution is to remove useless week day before passing the date string into strtotime, example:

<?php
   $date_string
= "Sun, 26 Oct 0010 12:00:00 +0100";
   if( (
$comma_pos = strpos($date_string, ',')) !== FALSE )
     
$date_string = substr($date_string, $comma_pos + 1);
  
$d3 = strtotime($date_string);
?>
up
-2
fuhrysteve at gmail dot com
13 years ago
Here's a hack to make this work for MS SQL's datetime junk, since strtotime() has issues with fractional seconds.

<?php

$MSSQLdatetime
= "Feb  7 2009 09:48:06:697PM";
$newDatetime = preg_replace('/:[0-9][0-9][0-9]/','',$MSSQLdatetime);
$time = strtotime($newDatetime);
echo
$time."\n";

?>
up
-5
Sui Dream
4 years ago
It was really pazzling to me to read about parsing a string into a Unix timestamp relative to both January 1 1970 00:00:00 UTC and the second parameter. Maybe it worth noting that the second parameter is for relative dates (like "+1 day").
To Top