PHP 5.6.30 Released

strtotime

(PHP 4, PHP 5, PHP 7)

strtotime 英文形式の日付を Unix タイムスタンプに変換する

説明

int strtotime ( string $time [, int $now = time() ] )

この関数は英語の書式での日付を含む文字列が指定されることを期待しており、 now で与えられたその形式から Unix タイムスタンプ (1970 年 1 月 1 日 00:00:00 UTC からの経過秒数) への変換を試みます。 now が指定されていない場合は現在日時に変換します。

この関数の各パラメータでは、パラメータ内でタイムゾーンを指定しない限りはデフォルトのタイムゾーンを使います。 意図的にそうする場合は別として、パラメータごとにタイムゾーンを変えてしまったりしないように気をつけましょう。 デフォルトのタイムゾーンを定義する方法については date_default_timezone_get() を参照ください。

パラメータ

time

日付/時刻 文字列。有効な書式については 日付と時刻の書式 で説明しています。

now

返される値を計算するために使用されるタイムスタンプ。

返り値

成功時はタイムスタンプ、そうでなければ FALSE を返します。 PHP 5.1.0 以前ではこの関数は失敗時に -1 を返します。

エラー / 例外

すべての日付/時刻関数は、 有効なタイムゾーンが設定されていない場合に E_NOTICE を発生させます。また、システム設定のタイムゾーンあるいは環境変数 TZ を使用した場合には E_STRICT あるいは E_WARNING を発生させます。 date_default_timezone_set() も参照ください。

変更履歴

バージョン 説明
5.3.0 PHP 5.3.0 より前のバージョンでは、 strtotime() の引数 timethis weekprevious weeklast weeknext week を指定すると、現在日時から数えて 7 日単位という解釈になっていました。 Monday から Sunday までという単位は考慮していませんでした。
5.3.0 PHP 5.3.0 より前のバージョンでは、24:00 は無効なフォーマットとされており strtotime()FALSE を返していました。
5.2.7 5.2.7 より前の PHP 5 では、「ある月の何回目の何曜日」 を取得するときにもしその月の初日がその曜日だった場合、 タイムスタンプが間違って一週間追加されてしまっていました。 これは 5.2.7 以降のバージョンでは修正されています。
5.1.0 失敗時に -1 の代わりに FALSE を返すようになりました。
5.1.0

タイムゾーンがおかしい場合に E_STRICTE_NOTICE が発生するようになりました。

5.0.2 5.0.2 までの PHP 5 では、"now" やその他の相対時刻は誤って当日の真夜中から計算されます。 他のバージョンでは、これは正しく現在時刻から計算されます。
5.0.0 マイクロ秒も受け付けるようになりましたが、指定してもそれは無視されます。

例1 A 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";
?>

例2 失敗のチェック

<?php
$str 
'Not Good';

// PHP 5.1.0 以前では、false の代わりに -1 と比較する
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);
}
?>

注意

注意:

年を 2 桁の数値で指定した場合、その値が 00-69 なら 2000-2069 に、 70-99 なら 1970-1999 にそれぞれ変換されます。 32 ビットシステム上での相違点 (2038-01-19 03:14:07 までの日付しか表せない) については以下の注意を参照ください。

注意:

タイムスタンプの有効な範囲は、通常、Fri, 13 Dec 1901 20:45:54 UTC から Tue, 19 Jan 2038 03:14:07 UTC までです (これらは、32 ビット符号付整数の最大及び最小に一致します)。

全てのプラットフォームが負のタイムスタンプをサポートしている わけではありませんので、PHP 5.1.0 より前のバージョンでは、日付の範囲が Unix エポック以前にはならないかも知れません。 これは、例えば Windows やいくつかの Linux ディストリビューション、 いくつかの他のオペレーティングシステムでは 1970 年 1 月 1 日以前の日付では動作しない事を意味しています。

64 ビット版の PHP では、タイムスタンプの有効範囲は事実上無制限です。 というのも、64 ビットでは過去側も未来側も約 2930 億年を表せるからです。

注意:

m/d/y あるいは d-m-y といった書式の曖昧さを解決する際には、区切り文字を利用します。スラッシュ (/) で区切られている場合はアメリカ風の m/d/y とみなし、ダッシュ (-) あるいはドット (.) で区切られている場合はヨーロッパ風の d-m-y であるとみなします。 しかし、年を二桁で表して区切り文字がダッシュ (-) である場合は、 y-m-d であるとみなします。

このような曖昧さを避けるためにも、ISO 8601 形式 (YYYY-MM-DD) を使うか、可能であれば DateTime::createFromFormat() を使うことを推奨します。

注意:

この関数を使って日付の足し算や引き算を行うことはおすすめできません。 PHP 5.3 以降なら DateTime::add()DateTime::sub() を、そして PHP 5.2 なら DateTime::modify() を使いましょう。

参考

add a note add a note

User Contributed Notes 31 notes

up
447
sam at frontiermedia dot net dot au
6 years ago
I've had a little trouble with this function in the past because (as some people have pointed out) you can't really set a locale for strtotime. If you're American, you see 11/12/10 and think "12 November, 2010". If you're Australian (or European), you think it's 11 December, 2010. If you're a sysadmin who reads in ISO, it looks like 10th December 2011.

The best way to compensate for this is by modifying your joining characters. Forward slash (/) signifies American M/D/Y formatting, a dash (-) signifies European D-M-Y and a period (.) signifies ISO Y.M.D.

Observe:

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

Hope this helps someone!
up
60
kumar AT swatantra.info Swatantra Kumar
3 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
59
Stefan Kunstmann
6 years ago
UK dates (eg. 27/05/1990) won't work with strotime, even with timezone properly set.

/*
However, if you just replace "/" with "-" it will work fine.
<?php
$timestamp
= strtotime(str_replace('/', '-', '27/05/1990'));
?>
*/

[red., derick]: What you instead should do is:

<?php
$date
= date_create_from_format('d/m/y', '27/05/1990');
?>

That does not make it a timestamp, but a DateTime object, which is much more versatile instead.
up
44
cristinawithout
4 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
6
joe at strtotime dot co dot uk
1 year ago
A useful testing tool for strtotime() and unix timestamp conversion:
http://strtotime.co.uk/
up
7
Killermonk
7 years ago
You are not restricted to the same date ranges when running PHP on a 64-bit machine. This is because you are using 64-bit integers instead of 32-bit integers (at least if your OS is smart enough to use 64-bit integers in a 64-bit OS)

The following code will produce difference output in 32 and 64 bit environments.

var_dump(strtotime('1000-01-30'));

32-bit PHP: bool(false)
64-bit PHP: int(-30607689600)

This is true for php 5.2.* and 5.3

Also, note that the anything about the year 10000 is not supported. It appears to use only the last digit in the year field. As such, the year 10000 is interpretted as the year 2000; 10086 as 2006, 13867 as 2007, etc
up
13
michal dot kocarek at brainbox dot cz
7 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
3
Travis Pulley
7 years ago
Be aware that if you are running 5.2.8, there is a memory leak with this function and it could cost someone valuable time finding out what the problem was. Per usual, running the latest (minor) version tends to be a good idea.

See here: http://bugs.php.net/bug.php?id=46889
up
11
me at will morgan dot co dot you kay
4 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
6
php at davidstockton dot com
7 years ago
Adding a note to an already long page:

Try to be as specific as you can with the string you pass in.  For example

<?php
echo date('F', strtotime('February'));
?>

is not specific enough.  Depending on the day of the month, you may get a different response.  For a non-leap year, you'll get March if the _current day of the month_ is the 29th, 30th or 31st.  If it's a leap year, you'll get March on the 30th or 31st of the month.  The same thing will happen on the 31st of any month when you pass in the name of any month with less than 31 days.  This happens because the strtotime() function will fill in missing parts from the current day.

Assuming today is July 31, the timestamp returned by strtotime('February') will ultimately be seen as February 31 (non-existant obviously), which then is interpreted as March 3, thus giving a month name of March.

Interestingly, adding the year or the day will give you back the expected month.
up
6
kyle at frozenonline dot com
13 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
5
Michael Muryn (MickoZ)
5 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
2
nyctimus at yahoo dot com
6 years ago
strtotime() produces different output on 32 and 64 bit systems running PHP 5.3.3 (as mentioned previously).  This affects the "zero date" ("0000-00-00 00:00:00") as well as dates outside the traditional 32 date range.

strtotime("0000-00-00 00:00:00") returns FALSE on a 32 bit system.
strtotime("0000-00-00 00:00:00") returns -62169955200 on a 64 bit system.
up
4
Annomoys
5 years ago
Strtotime() can be used to loop through date range.
as follows

<?php
$start
= strtotime('2009-02-01');
$end = strtotime('2009-03-10');
$date = $start;
while(
$date < $end)
{

  
//write your code here
  
$date = strtotime("+1 day", $date);(counter)

}

?>
up
2
x at xero dot nu
6 years ago
strtotime is awesome for converting dates.
in this example i will make an RSS date, an
ATOM date, then convert them to a human
readable m/d/Y dates.

<?php
$rss
= date("r");
$atom = date("c");
$human1 = date('m/d/Y', strtotime($rss));
$human2 = date('m/d/Y', strtotime($atom));

echo
$rss."<br />".$atom."<br />".$human1."<br />".$human2;
?>
up
1
chris at teamsiems dot com
7 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
1
marcodemaio at vanylla dot it
6 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
Anonymous
7 years ago
This function DOES NOT work from left-to-right as one would think. This function parses the string as a whole, then applies the intervals by size (year, month, ...). Take the following example:

<?php
$Date
= strtotime('2011-02-22'); // February 22nd, 2011. 28 days in this month, 29 next year.
echo date('n/j/Y', strtotime('+1 year, +7 days', $Date)); // add 1 year and 7 days. prints 2/29/2012
echo "<br />";
echo
date('n/j/Y', strtotime('+7 days, +1 year', $Date)); // add 7 days and 1 year, but this also prints 2/29/2012
echo "<br />";
echo
date('n/j/Y', strtotime('+1 year', strtotime('+7 days', $Date))); // this prints 3/1/2012, what the 2nd would do if it was left-to-right
?>
up
1
trurl at mcbyte dot net
10 months ago
Be carefull with weekdays names
<?php echo date('r',strtotime("Thursday 01:15")), "\n"; ?>
returns something like "Thu, 17 Mar 2016 01:15:00 +0200"
but
<?php echo date('r',strtotime("Thursdays 01:15")), "\n"; ?>
returns "Thu, 17 Mar 2016 09:15:00 +0200".

So "s" at end mean "+8 hours".
up
-1
Sooraj dot abbasi at gmail dot com
6 months ago
Here is some code may be helpful for developers. I am setting a date interval of one month in my current date for next three years. and here is my code for that.

<?php

$date
='4-4-2016';// your start date.

for($i=0;$i<=36;$i++)
{
   
$d = new DateTime($date);
   
$d->modify('+1 months');
    echo
$date=$d->format('d-m-Y');
    echo
"<br>";
}

?>
up
0
gabriel dot rempel at gmail dot com
1 year ago
// small function auto detect to convert date

function formatDate($date)
{
    if (strpos($date,'/') !== false) :
        $date = str_replace('/', '-', $date);
        $date = date('Y-m-d h:i:s', strtotime($date));
    else :
        $date = date('d-m-Y h:i:s', strtotime($date));
        $date = str_replace('-', '/', $date);
    endif;
    return $date;
}
up
0
peixoto at live dot com
2 years ago
<?php strtotime('-5 weeks monday') ?> returns the monday of 5 weeks ago.
up
0
a dot fruchi at bit-runners dot com
5 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
kooshal at live dot com
7 years ago
when using PHP 5.3, you must use date_default_timezone_set() to set the time zone otherwise you will get warning similar to this (if you have display_errors=On)—

Warning: date() [function.date]: It is not safe to rely on the system's timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected 'Asia/Dubai' for '4.0/no DST' instead in path/to/php/script.php
on line ##

Example:
date_default_timezone_set('Indian/Mauritius');

For a list of supported timezones in PHP, see http://www.php.net/manual/en/timezones.php
up
0
viper7 at viper-7 dot com
7 years ago
Observed date formats that strtotime expects, it can be quite confusing, so hopefully this makes things a little clearer for some.

mm/dd/yyyy - 02/01/2003  - strtotime() returns : 1st February 2003
mm/dd/yy   - 02/01/03    - strtotime() returns : 1st February 2003
yyyy/mm/dd  - 2003/02/01 - strtotime() returns : 1st February 2003
dd-mm-yyyy - 01-02-2003  - strtotime() returns : 1st February 2003
yy-mm-dd   - 03-02-01    - strtotime() returns : 1st February 2003
yyyy-mm-dd - 2003-02-01  - strtotime() returns : 1st February 2003
up
0
fuhrysteve at gmail dot com
7 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
-1
Anonymous
2 years ago
Be aware that you cannot rely on this function alone to validate a date, as it will accept insane dates like the 31st of February.

Also, the '... week' functionality by itself may not do what you expect. If used on a Sunday, 'next week' will not return a timestamp of the next Monday, but of the Monday after that. Similarly, a timestamp for the Monday of the current week is returned when 'previous/last week' is used and 'this week' returns a stamp of the Monday of the next week (i.e. the following day). This is not the 'week starts on Sunday' effect, as that would mean all the timestamps returned would have to be on a Sunday and none of them are.
up
-1
Andrey Kabakchiev
1 year ago
Actually the top-voted comment from 'sam at frontiermedia dot net dot au' is not quite right, as is the documentation Note. The correct assumptions made by strtotime() are:

Forward slashes (/) assume US formatted dates, e.g mm/dd/yy

Periods (.) assume Non-US dates, e.g dd.mm.yy

Hypens (-) assume ISO 8601 (ATOM) formatted dates, e.g yy-mm-dd
up
-4
Tim
6 years ago
Unlike "yesterday 14:00", "14:00 yesterday" will return 00:00 of yesterday.
up
-8
sgutauckis
10 years ago
The following might produce something different than you might expect:
<?php
   
echo date('l, F jS Y', strtotime("third wednesday", strtotime("2006-11-01"))) . "<br>";
    echo
date('l, F jS Y', strtotime("third sunday", strtotime("2006-01-01")));
?>
Produces:
Wednesday, November 22nd 2006
Sunday, January 22nd 2006

The problem stems from strtotime when the requested day falls on the date passed to strtotime. If you look at your calendar you will see that they should return:

Wednesday, November 15th 2006
Sunday, January 15th 2006

Because the date falls on the day requested it skips that day.
up
-4
me at ramynasr dot com
1 year ago
There were a lot of comments about the right date format to parse the standard apache log time properly.

<?php
$string
= '[26/Oct/2015:15:42:26 -0500]';

$format = '[d/M/Y:H:i:s T]';

$date  = DateTime::createFromFormat($format, $string);
?>
To Top