SymfonyWorld Online 2022 Winter Edition

strtotime

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

strtotimeInterpreta qualquer descrição de data/hora em texto em inglês em timestamp Unix

Descrição

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

A função espera que seja informada uma string contendo um formato de data em inglês US, e tentará interpretá-lo para um timestamp Unix (o número de segundos desde January 1 1970 00:00:00 GMT), relativo ao timestamp dado em now, ou a hora atual se now não é fornecido.

Cada parâmetro desta função utiliza o fuso horário padrão, a não ser que um fuso horário seja especificado neste parâmetro. Tome cuidado para não utilizar fusos horários diferentes em cada um dos parâmetros a não ser que seja o pretendido. Veja a função date_default_timezone_get() para verificar as diversas formas de definir um fuso horário padrão.

Parâmetros

time

Uma string data/hora. Valores válidos são explicados em Formatos de Data e Hora.

now

O timestamp que será utilizado como base no cálculo das datas relativas.

Valor Retornado

Retorna um timestamp em sucesso, false caso contrário. Antes do PHP 5.1.0, esta função podia retornar -1 em falha.

Erros

Todas as chamadas a funções de data/hora gerarão um E_NOTICE se o fuso horário não for válido, e/ou uma mensagem E_STRICT ou E_WARNING se utilizar as configurações do sistema ou a variável de ambiente TZ. Veja também date_default_timezone_set()

Exemplos

Exemplo #1 Exemplo da função 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";
?>

Exemplo #2 Checando por falha

<?php
$str 
'Not Good';

// em versões antes do PHP 5.1.0 você compararia com -1, ao invés de false
if (($timestamp strtotime($str)) === false) {
    echo 
"The string ($str) is bogus";
} else {
    echo 
"$str == " date('l dS \o\f F Y h:i:s A'$timestamp);
}
?>

Notas

Nota:

Se o número do ano for especificado no formato com dois dígitos, o valor entre 00-60 será mapeado para 2000-2069 e 70-99 para 1970-1999. Veja as notas a seguir para possíveis diferenças em sistemas 32bit (as datas possíveis acabam em 2038-01-19 03:14:07),

Nota:

O intervalo válido de um timestamp é tipicamente de Fri, 13 Dec 1901 20:45:54 GMT até Tue, 19 Jan 2038 03:14:07 GMT. (Estas são datas que correspondem aos valores máximos e mínimos para um inteiro sem sinal em sistemas 32-bit.)

Em versões anteriores ao PHP 5.1.0, nem todas as plataformas suportam timestamps negativos, então a faixa de sua data pode ser limitada a valores inferiores a Era Unix. Isto significa que datas antes de Jan 1, 1970 não funcionam no Windows, algumas distribuições do Linux, e outros sistemas operacionais.

Em versões do PHP em 64-bit, a faixa válida de um timestamp é praticamente infinita, já que 64 bits pode representar aproximadamente 293 bilhões de anos em ambas direções.

Nota:

Datas nos formatos m/d/y e d-m-y são diferenciadas observando o separador entre os vários componentes: se o separador é uma barra (/), o formato Americano m/d/y é utilizado; enquanto que, se o separador for um traço (-) ou um ponto (.), o formato Europeu d-m-y será utilizado. Entretanto, se o ano foi informado no formato de dois dígitos e o separador for um traço (-, a string de data será interpretada como y-m-d.

Para evitar uma ambiguidade em potencial, o melhor é utilizar datas que seguem a ISO 8601 (YYYY-MM-DD) ou o método DateTime::createFromFormat() sempre que possível.

Nota:

O uso desta função para operações matemáticas não é recomendado. É melhor a utilização dos métodos DateTime::add() e DateTime::sub() no PHP 5.3 e superior, ou o método DateTime::modify() no PHP 5.2.

Veja Também

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
12 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
4 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
3 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
28 days 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