Web студия "GrandView"
  Главная   Написать Контакты
   
   
О проекте
Руководство php
 

strtotime

(PHP 3 >= 3.0.12, PHP 4, PHP 5)

strtotime -- Преобразует текстовое представление даты на английском языке в метку времени Unix

Описание

int strtotime ( string time [, int now] )

Первым параметром функции должна быть строка с датой на английском языке, которая будет преобразована в метку времени относительно метки времени, переданной в now, или текущего времени, если аргумент now опущен. В случае ошибки возвращается -1.

Функция strtotime() использует GNU формат даты, поэтому рекомендуется ознакомиться с руководством GNU Date Input Formats, где описывается синтаксис аргумента time.

Пример 1. Пример использования функции 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';
if ((
$timestamp = strtotime($str)) === -1) {
    echo
"Строка ($str) недопустима";
} else {
    echo
"$str == " . date('l dS of F Y h:i:s A', $timestamp);
}
?>

Замечание: Для большинства систем допустимыми являются даты с 13 декабря 1901, 20:45:54 GMT по 19 января 2038, 03:14:07 GMT. (Эти даты соответствуют минимальному и максимальному значению 32-битового целого со знаком). Для Windows допустимы даты с 01-01-1970 по 19-01-2038. Не все платформы поддерживают отрицательные метки времени, поэтому даты ранее 1 января 1970 г. не поддерживаются в Windows, некоторых версиях Linux и некоторых других операционных системах.



time> <strptime
Last updated: Sat, 27 Jan 2007
 
add a note add a note User Contributed Notes
strtotime
Beat
01-Oct-2007 03:41
Here the workaround to the bug of strtotime() found in my previous comment on finding the exact date and time of "3 months ago of last second of this year", using mktime() properties on dates instead of strtotime(), and which seems to give correct results:

<?php
// check for equivalency
$basedate = strtotime("31 Dec 2007 23:59:59");
$timedate = mktime( 23, 59, 59, 1, 0, 2008 );
echo
"$basedate $timedate ";         // 1199141999 1199141999 : SO THEY ARE EQUIVALENT

// workaround, as mktime knows to handle properly offseted dates:
$date1 = mktime( 23, 59, 59, 1 - 3, 0, 2008 );
echo
date("j M Y H:i:s", $date1);  // 30 Sep 2007 23:59:59 CORRECT

?>
Beat
01-Oct-2007 01:36
Some surprisingly wrong results (php 5.2.0): date and time seem not coherent:

<?php
// Date: Default timezone     Europe/Berlin   (which is CET)
// date.timezone    no value
$basedate = strtotime("31 Dec 2007 23:59:59");
$date1 = strtotime("-3 months", $basedate);
echo
date("j M Y H:i:s", $date1);  // 1 Oct 2007 23:59:59 WRONG

$basedate = strtotime("31 Dec 2007 23:59:59 CET");
$date1 = strtotime("-3 months", $basedate);
echo
date("j M Y H:i:s", $date1);  // 1 Oct 2007 23:59:59 WRONG

$basedate = strtotime("31 Dec 2007 23:59:59 GMT");
$date1 = strtotime("-3 months", $basedate);
echo
date("j M Y H:i:s", $date1);  // 1 Oct 2007 00:59:59 CORRECT

$basedate = strtotime("31 Dec 2007 22:59:59 GMT");
$date1 = strtotime("-3 months", $basedate);
echo
date("j M Y H:i:s", $date1);  // 1 Oct 2007 23:59:59 WRONG AGAIN

$basedate = strtotime("31 Dec 2007 00:00:00 GMT");
$date1 = strtotime("-3 months", $basedate);
echo
date("j M Y H:i:s", $date1);  // 1 Oct 2007 01:00:00 CORRECT

$basedate = strtotime("31 Dec 2007 00:00:00 CET");
$date1 = strtotime("-3 months", $basedate);
echo
date("j M Y H:i:s", $date1);  // 1 Oct 2007 00:00:00 WRONG AGAIN

$basedate = strtotime("31 Dec 2007 00:00:01");
$date1 = strtotime("-3 months", $basedate);
echo
date("j M Y H:i:s", $date1);  // 1 Oct 2007 00:00:01 WRONG AGAIN

?>
ragearc at gmail dot com
14-Sep-2007 02:12
PHP 5.1.0 and above might overcome the limitation of parsing dates earlier than 1970, but they still do it at a much slower pace (About 0.5 seconds). Just a note for anyone trying to use this function for this purpose.
btherl at yahoo dot com dot au
02-Sep-2007 07:33
Another inconsistency between versions:

print date('Y-m-d H:i:s', strtotime('today')) . "\n";
print date('Y-m-d H:i:s', strtotime('now')) . "\n";

In PHP 4.4.6, "today" and "now" are identical, meaning the current timestamp.

In PHP 5.1.4, "today" means midnight today, and "now" means the current timestamp.
mhamill at computer dot org
27-Aug-2007 05:40
I am thinking this function may have a bug in it. Can anyone explain why strtotime when parsing two RSS-2 newfeeds with ISO-2822 timestamps for the pubDate can give true in the first case and false in the second case?

Wed, 22 Aug 2007 21:23:51 -0500 (This works)

Mon, 27 Aug 2007 12:47:06 +0000 (This returns false)

I am using PHP 5.1.2.
JustinB at at at harvest dot org
15-Aug-2007 07:42
@smartalco:

Since the first day of a month is always the first (unless I missed something in History), you could save yourself some overhead from the second strtotime() by forcing the day manually:

<?php
echo date('l, F jS Y', strtotime('August 1 2007'));
// Outputs "Wednesday, August 1st 2007"
?>

While it's a relatively minor performance difference in a small script, it would be compounded significantly in larger applications or loops.
smartalco
26-Jul-2007 09:19
a simple way to find the first day of a month

<?php
echo date('l, F jS Y', strtotime("first day", strtotime("August 0 2007")));
?>

result:
Wednesday, August 1st 200
csnyder at chxo dot com
20-Jul-2007 12:23
Previous comments regarding dates prior to 1970 may be out of date.
In PHP 5.2.3 on Linux:

<?php
$timestamp
= strtotime( "February 26, 1946" );
print
date( 'Y-m-d', $timestamp );
?>

Output is "1946-02-26", as expected.
ThomasK
19-Jul-2007 06:13
A major difference in behavior between PHP4x and newer 5.x versions is the handling of "illegal" dates: With PHP4, strtotime("2007/07/55") gave a valid result that could be used for further calculations.
This does not work anymore at PHP5.xx (here: 5.2.1), instead something like strtotime("$dayoffset_relative_to_today days","2007/07/19") is to be used.
olav dot morkrid at gmail dot com
07-Jul-2007 10:47
when using strtotime("wednesday"), you will get different results whether you ask before or after wednesday, since strtotime always looks ahead to the *next* weekday.

strtotime() does not seem to support forms like "this wednesday", "wednesday this week", etc.

the following function addresses this by always returns the same specific weekday (1st argument) within the *same* week as a particular date (2nd argument).

function weekday($day="", $now="") {

  $now = $now ? $now : "now";
  $day = $day ? $day : "now";

  $rel = date("N", strtotime($day)) - date("N");

  $time = strtotime("$rel days", strtotime($now));

  return date("Y-m-d", $time);

}

example use:

weekday("wednesday"); // returns wednesday of this week
weekday("monday, "-1 week"); // return monday the in previous week

ps! the ? : statements are included because strtotime("") without gives 1 january 1970 rather than the current time which in my opinion would be more intuitive...
Ian Fieggen
30-Jun-2007 07:54
To calculate the last Friday in the current month, use strtotime() relative to the first day of next month:

<?php
$lastfriday
=strtotime("last Friday",mktime(0,0,0,date("n")+1,1));
?>

If the current month is December, this capitalises on the fact that the mktime() function correctly accepts a month value of 13 as meaning January of the next year.
matt
31-May-2007 08:10
Note about strtotime() when trying to figure out the NEXT month...

strtotime('+1 months'), strtotime('next month'), and strtotime('month') all work fine in MOST circumstances...

But if you're on May 31 and try any of the above, you will find that 'next month' from May 31 is calculated as July instead of June....
alanna at dramatis-personae dot com
12-May-2007 08:41
One more difference between php 4 and 5 (don't know when they changed this) but the string 15 EST 5/12/2007 parses fine with strtotime in php 4, but returns the 1969 date in php 5.  You need to add :00 to make it 15:00 so php can tell those are hours.  There's no change in php 4 when you do this.
Alan Gruskoff
07-Apr-2007 06:31
This function inputs a date sting and outputs an integer that is the internal representation of days that spreadsheets use. Post this value into a cell, then format that cell as a Date.

function conv_to_xls_date($Date) {
// Returns the Excel/Calc internal date integer from either an ISO date YYYY-MM-DD or MM/DD/YYYY formats.
    return (int) (25569 + (strtotime("$Date 12:00:00") / 86400));
}

example:

$Date = "04-07-2007";
$Days =  conv_to_xls_date($Date);

$Days will contain 39179
02-Mar-2007 03:29
SQL datetime columns have a much wider range of allowed values than a UNIX timestamp, and therefore this function is not safe to use to convert a SQL datetime column to something usable in PHP4.  Year 9999 is the limit for MySQL, which obviously exceeds the UNIX timestamp's capacity for storage.  Also, dates before 1970 will cause the function to fail (at least in PHP4, don't know about 5+), so for example my boss' birthday of 1969-08-11 returned FALSE from this function.

[red. The function actually supports it since PHP 5.1, but you will need to use the new object oriented methods to use them. F.e:
<?php
$date
= new DateTime('1969-08-11');
echo
$date->format('m d Y');
?>
]
sean at awesomeplay dot com
09-Feb-2007 12:29
Regarding the "NET" thing, it's probably parsing it as a time-zone.  If you give strtotime any timezone string (like PST, EDT, etc.) it will return the time in that time-zone.

In any case, you shouldn't use strtotime to validate dates.  It can and will give incorrect results.  As just one shining example:

Date: 05/01/2007

To most Americans, that's May 1st, 2007.  To most Europeans, that's January 5th, 2007.  A site that needs to serve people around the globe cannot use strtotime to validate or even interpret dates.

The only correct way to parse a date is to mandate a format and check for that specific format (preg_match will make your life easy) or to use separate form fields for each component (which is basically the same thing as mandating a format).
xurizaemon of the land of gmail
23-Jan-2007 01:17
Somewhere between PHP5.0 and PHP5.1.6, strtotime started accepting '.' (period, dot) as well as ':' (colon) as a time separator.

before: "2.30pm" == -1
after: "2.30pm" == 14:30

[red.: This is working since PHP 5.1.0]
LigH
16-Jan-2007 02:47
A hint not to misunderstand the second parameter:

The parameter "[, int now]" is only used for strings which describe a time difference to another timestamp.

It is not possible to use strtotime() to calculate a time difference by passing an absolute time string, and another timestamp to compare to!

Correct:

$day_before = strtotime("+1 day", $timestamp);
# result is a timestamp relative to another

Wrong:

$diff = strtotime("2007-01-15 11:40:00", time());
# result it the timestamp for the date in the string;
# because the string contains an absolute date and time,
# the second parameter is ignored!
# instead, use:
$diff = time() - strtotime("2007-01-15 11:40:00");
15-Oct-2006 02:50
Be careful, strtotime("+1 month", strtotime("2006-05-31"));
returns 2006-07-01!
sgutauckis
05-Oct-2006 12:02
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.
d_spagnoli at yahoo dot it
11-May-2006 03:18
The GNU manual page has moved, the new address is

http://www.gnu.org/software/shishi/manual/html_node/Date-input-formats.html
jacques dot malan at gmail dot com
11-Apr-2006 04:08
I have had some inconsistancies that was not immediately evident and suggested that strtotime treated my date formats in different ways.
I had trouble with the date format: d/m/Y

I eliminated the inconsistancies by changing the date format to one where (i guess) php does not try and guess the right format. In my case I changed it to the format (d-M-Y) in which case it worked.

Example when trying to find a person's age where:

//$date in format (d/m/Y) was inconsistant but fixed when in format (d-M-Y), e.g. (01-January-2001)

$age = (time() - strtotime($date))/(60*60*24*360);
kturner at kgt dot net
24-Jan-2006 10:18
It looks like in the latest release of PHP 5.1, when passing to strtotime this string "12/32/2005", it will now return the date "12/31/1969". (The previous versions would return "1/1/2006".)
matt at australiangamer dot com
17-Jan-2006 04:32
Regarding the previous post on strtotime() being used to convert mysql datetime strings, I agree that this is not widely realized.

Part of the reason for this is that it is only a relatively recent addition. Prior to PHP 5.0, though it might have been an earlier version, strtotime() would return -1 on a mysql datetime string.

If you're on a server that doesn't have a recent PHP version test your result before assuming this one works.
shaver at qspeed dot com
11-Jan-2006 08:13
I'm posting these here as I believe these to be design changes, not bugs.

For those upgrading from PHP 4 to PHP 5 there are a number of things that are different about strtotime that I have NOT seen documented elsewhere, or at least not as clearly. I confirmed these with two separate fresh installations of PHP 4.4.1 and PHP 5.1.1.

1) Given that today is Tuesday: PHP4 "next tuesday" will return today. PHP5 "next tuesday" will actually return next tuesday as in "today +1week". Note that behavior has NOT changed for "last" and "this". For the string "last tuesday" both PHP4 and PHP5 would return "today -1week".  For the string "this tuesday" both PHP4 and PHP5 would return "today".

2) You cannot include a space immediately following a + or - in PHP 5. In PHP4 the string "today + 1 week" works great. in PHP5 the string must be "today +1 week" to correctly parse.

3) (Partially noted in changelog.) If you pass php4 a string that is a mess ("asdf1234") it will return -1. If you in turn pass this to date() you'll get a warning like: Windows does not support dates prior to midnight. This is pretty useful for catching errors in your scripts. In PHP 5 strtotime will return FALSE which causes date() to return 12/31/69. Note that this is true of strings that might appear right such as "two weeks".

4) (Partially noted in changelog.) If you pass php4 an empty string it will error out with a "Notice: strtotime(): Called with empty time parameter". PHP5 will give no notice and return the current date stamp. (A much preferred behavior IMO.)

5) Some uppercase and mixed-case strings no longer parse correctly. In php4 "Yesterday" would parse correctly. In php5 "Yesterday" will return the infamous 1969 date. This is also true of Tomorrow and Today. [Red. This has been fixed in PHP already]

6. The keyword "previous" is supported in PHP5. (Finally!)

Good luck with your upgrades. :)
 -Will
Mr Obvious
10-Jan-2006 06:10
@ nick at fortawesome dot co dot uk
regarding 'month' vs 'next month'

Not sure what version of PHP you found those results on, however with PHP 4.4.0,
<?PHP
$time1
=strtotime('next month');
$time2=strtotime('month');
?>
produce the exact same result.
15-Dec-2005 05:31
Note that by default strtotime( ) considers the string time like a local time.
If your input string time is GMT/UTC do :

<?php
    $date
= '2005-12-25 00:56:27 GMT' ; // Note the timezone specification
   
$time = strtotime($date) ;
    echo
date('d/m/Y H:i:s', $time) ; // $date will be correctly localized
    //
Новости
11 июля 2007
Сайт запущен
© 2007 info@grandviewstudio.com

Deprecated: Function set_magic_quotes_runtime() is deprecated in /home/sites/grandviewstudiocom/www/65f67d67a94ad980786580ae69e11c07/sape.php on line 324

Deprecated: Function set_magic_quotes_runtime() is deprecated in /home/sites/grandviewstudiocom/www/65f67d67a94ad980786580ae69e11c07/sape.php on line 330
Z058440144362 Z348613067571