strtotime

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

strtotimeWandelt eine textuelle englische Datums- und Zeitbeschreibung in einen Unix-Zeitstempel um

Beschreibung

strtotime(string $datetime, ?int $baseTimestamp = null): int|false

Diese Funktion erwartet eine Zeichenkette mit einem Datum im englischen Datumsformat und versucht, dieses Format in einen Unix-Zeitstempel (die Anzahl der Sekunden seit dem 1. Januar 1970 00:00:00 UTC) zu übersetzen. Die Angabe wird relativ zum Zeitstempel ausgewertet, der im Parameter baseTimestamp übergebenen wurde, oder, falls baseTimestamp nicht übergeben wurde, relativ zur aktuellen Zeit. Das Format der Zeichenkette, die das auszuwertende Datum enthält, ist in Unterstützte Datums- und Zeitformate definiert, wobei einige Feinheiten zu beachten sind. Es wird dringend empfohlen, sich dort mit allen Details vertraut zu machen.

Warnung

Der Unix-Zeitstempel, den diese Funktion zurückgibt, enthält keine Informationen über Zeitzonen. Um Berechnungen mit Datums- und Zeitwerten durchzuführen, sollte das leistungsfähigere DateTimeImmutable verwendet werden.

Jeder Parameter dieser Funktion verwendet die Standardzeitzone, es sei denn, im betreffenden Parameter wird eine Zeitzone angegeben. Es ist darauf zu achten, nicht etwa verschiedene Zeitzonen je Parameter zu verwenden, außer es ist beabsichtigt. Die verschiedenen Möglichkeiten, die Standardzeitzone zu definieren, sind date_default_timezone_get() zu entnehmen.

Parameter-Liste

datetime

Ein Datums/Zeit Zeichenkette. Gültige Formate werden unter Datums- und Zeitformate erläutert.

baseTimestamp

Der Zeitstempel, der als Basis zur Berechnung relativer Daten verwendet wird.

Rückgabewerte

Gibt im Erfolgsfall einen Zeitstempel zurück, andernfalls false.

Fehler/Exceptions

Jeder Aufruf der Datums- und Zeitfunktionen generiert einen Fehler der Stufe E_WARNING, wenn die Zeitzone ungültig ist. Siehe auch date_default_timezone_set()

Changelog

Version Beschreibung
8.0.0 baseTimestamp ist nun nullable (akzeptiert den null-Wert).

Beispiele

Beispiel #1 Ein strtotime()-Beispiel

<?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";
?>

Beispiel #2 Test auf Fehler

<?php
$str 
'Not Good';

if ((
$timestamp strtotime($str)) === false) {
    echo 
"Die Zeichenkette ($str) ist fehlerhaft.";
} else {
    echo 
"$str == " date('l dS \o\f F Y h:i:s A'$timestamp);
}
?>

Anmerkungen

Hinweis:

"Relatives" Datum bedeutet in diesem Fall auch, dass nicht angegebene Komponenten des Datums-/Zeitstempels unverändert aus dem baseTimestamp übernommen werden. Das heißt, dass strtotime('February') am 31. Mai 2022 als 31 February 2022 interpretiert wird, was zum Zeitstempel 3 March führt (in einem Schaltjahr wäre es 2 March). Stattdessen strtotime('1 February') oder strtotime('first day of February') zu verwenden, würde dieses Problem vermeiden.

Hinweis:

Wenn die Angabe der Jahreszahl zweistellig erfolgt, werden Werte von 0-69 den Jahren 2000-2069 zugeordnet, die Werte 70-99 ergeben die Jahreszahlen 1970-1999. Zu möglichen Unterschieden auf 32-Bit-Systemen (mögliche Datumsangaben könnten am 2038-01-19 03:14:07 enden) ist der folgende Hinweis zu beachten.

Hinweis:

Der gültige Bereich eines Zeitstempels liegt typischerweise zwischen Fri, 13 Dec 1901 20:45:54 UTC und Tue, 19 Jan 2038 03:14:07 UTC (das sind die Datumsangaben, die dem minimalen und maximalen Wert eines vorzeichenbehafteten 32-bit Integer entsprechen).

Bei 64-Bit-Versionen von PHP ist der gültige Bereich für Zeitstempel praktisch unendlich groß, da 64 Bit etwa 293 Milliarden Jahre in beide Richtungen darstellen können.

Hinweis:

Es ist nicht empfehlenswert, diese Funktion für mathematische Berechnungen zu verwenden. Dafür sollten stattdessen DateTime::add() und DateTime::sub() verwendet werden.

Siehe auch

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)
11 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