Historically, the "English" text to date parsers in PHP only accept the illogical American format of "mm/dd/yyyy". In this case, don't use strtotime, construct the date manually e.g :
<?php
$r = "29/9/2008";
$date = explode("/",$r);
echo date("D d M",mktime(0,0,0,$date[1],$date[0],$date[2]))."\n";
?>
strtotime
(PHP 4, PHP 5)
strtotime — Procesar cualquier descripción textual de fecha/hora en Inglés convirtiéndola en una timestamp de UNIX.
Descripción
La función espera que se le pase una cadena conteniendo una fecha en formato Inglés e intentará procesarla y convertirla a una timestamp (muestra de tiempo) de UNIX relativa a la timestamp proporcionada en ahora , o la hora actual si no se indica ninguna. Si falla, devolverá -1.
Dado que strtotime() obra de acuerdo con la sintaxis de fechas de GNU, puede echar un vistazo a la página del manual GNU titulada » Date Input Formats (Formatos de entrada de fechas). La sintaxis descrita ahí es válida para el parátro hora .
Example #1 Ejemplos con strtotime()
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";
Example #2 Comprobando si falla
$str = 'No válida';
if (($timestamp = strtotime($str)) === -1) {
echo "La cadena ($str) no es válida.";
} else {
echo "$str == ". date('l dS of F Y h:i:s A',$timestamp);
}
Note: El rango válido de una timestamp suele ser desde Fri, 13 Dec 1901 20:45:54 GMT (Viernes, 13 de diciembre) a Tue, 19 Jan 2038 03:14:07 GMT (Martes, 19 de enero). (Estas son las fechas que corresponden a los valores mínimo y máximo de un entero con signo de 32 bits.)
strtotime
26-Sep-2008 03:25
25-Sep-2008 07:48
Some simple function to find all periods in dates list
<?php
function extract_periods($dates,$delimiter="="){
sort($dates);
$period=Array();
$date_from=$date_to="";
$k=0;
foreach ($dates as $key=>$value) {
if (empty($date_from)) $date_from=$value;
else {
$k++;
$tmp_date=strtotime("+ ".$k." day",strtotime($date_from));
if (date("Y-m-d", $tmp_date)!=$value) {
$tmp_date=strtotime("+ ".($k-1)." day",strtotime($date_from))
$date_to=date("Y-m-d",$tmp_date);
if ($date_from!=$date_to)
$period[]=$date_from.$delimiter.$date_to;
else
$period[]=$date_from;
$date_from=$value;
$k=0;
}
}
}
return $period;
}
Use:
$dates = Array(
"2008-09-30",
"2008-09-28",
"2008-09-26",
"2008-09-27",
"2008-09-25");
$periods = extract_periods($dates);
foreach ($periods as $value)
echo $value."<br />";
?>
Output:
2008-09-25=2008-09-28
2008-09-30
12-Sep-2008 08:35
I'm find some simple way to find all days between a couple of dates
(Все дни между двумя датами):
<?php
$dt=Array("27.01.1985","12.09.2008");
$dates=Array();
$i=0;
while (strtotime($dt[1])>=strtotime("+".$i." day",strtotime($dt[0])))
$dates[]=date("Y-m-d",strtotime("+".$i++." day",strtotime($dt[0])));
foreach ($dates as $value) echo $value."<br />";
?>
12-Sep-2008 06:31
Finding the starting date of next week:
strtotime("next week") won't work since it will be interpreted as "current day + 7 days".
Solution: Find current week's first day, then add 7 days:
<?php
$startTsCurrentWeek = mktime(0, 0, 0, date('m'), date('d') - date('w'), date('Y'));
$startTsNextWeek = $startTsCurrentWeek + (7*86400);
$startTsPreviousWeek = $startTsCurrentWeek - (7*86400);
?>
09-Sep-2008 11:39
A little function to add 2 time lenghts. Enjoy !
<?php
function AddPlayTime ($oldPlayTime, $PlayTimeToAdd) {
$pieces = split(':', $oldPlayTime);
$hours=$pieces[0];
$hours=str_replace("00","12",$hours);
$minutes=$pieces[1];
$seconds=$pieces[2];
$oldPlayTime=$hours.":".$minutes.":".$seconds;
$pieces = split(':', $PlayTimeToAdd);
$hours=$pieces[0];
$hours=str_replace("00","12",$hours);
$minutes=$pieces[1];
$seconds=$pieces[2];
$str = $str.$minutes." minute ".$seconds." second" ;
$str = "01/01/2000 ".$oldPlayTime." am + ".$hours." hour ".$minutes." minute ".$seconds." second" ;
// Avant PHP 5.1.0, vous devez comparer avec -1, au lieu de false
if (($timestamp = strtotime($str)) === false) {
return false;
} else {
$sum=date('h:i:s', $timestamp);
$pieces = split(':', $sum);
$hours=$pieces[0];
$hours=str_replace("12","00",$hours);
$minutes=$pieces[1];
$seconds=$pieces[2];
$sum=$hours.":".$minutes.":".$seconds;
return $sum;
}
}
$firstTime="00:03:12";
$secondTime="02:04:34";
$sum=AddPlayTime($firstTime,$secondTime);
if ($sum!=false) {
echo $firstTime." + ".$secondTime." === ".$sum;
}
else {
echo "failed";
}
?>
03-Sep-2008 08:48
Rather a notice, but maybe important to share with everyone.
I am currently stationed at a company that works with php on an IBM i5. Now there are a few things that run slower. strtotime() is a good example.
Running the script we saw that this function on an i5 consumes a lot of time when you have a lot of records to process. Using it on a loopcount of 3000 (which we took as reference), we noticed that the script took 4 seconds longer than without the conversion. Imagine you doing this in an environment with more than just this conversion.
We came up with a simple solution: Calculate the date by using a preformatted string (preferably the datetime field directly from MySQL, just for the sake of performance).
We needed this conversion for our webapplication. Creating this function saves us 4 seconds on 3000 loops. Since we really need that more than once per loop, imagine the load (for your info, the script now took only 1 second in stead of 5, each loop about 0.0009s).
What you need to do is:
- Multiply the number of years minus 1 (you are in the last year) since 1970 with the number of days and then the number of seconds per day (don't foget leap years)
- Create a loop counting cumulating the number of days per months minus one (you are in the current month) and multiply it by the number seconds per day
- Add the number of days minus one (you are in the current day) and multiply that by the number of seconds in a day
- Multiply the number of hours by the number of seconds in an hour (normally 3600)
- Multiply the minutes by the number of seconds in a minute (which would still be 60)
- Add the seconds...
Hey, wait, when i do a backward conversion with date(.., $thatCalculatedTimestamp) it shows the right date and all, but it's one hour ahead.
True, you still need to adjust daylight saving time if your country uses this method.
Ok, that was a long story, but I just hope it is helpful.
Maybe it'll also create performance gain on other machines when you need this functionality.
If you have an other suqqgestion, please, I'm all ears.
Reerun...
03-Sep-2008 05:50
Note that in some builds of PHP 5 doing the following may return unexpected results:
<?php
$server_date = date("Y-m-d"); // Assumed GMT 0
$timezone_offset = -10; // GMT -10
$date = date("Y-m-d", strtotime($server_date . " +" . $timezone_offset . " hours"));
echo $date; // prints 1969-12-31
?>
What it boils down to is the strtotime function accepting the time offset "+-10 hours", which confuses the function. To be safe be sure to check signs for offset values, and only add the plus (+) sign for non-negative offsets.
03-Sep-2008 12:51
strtotime returns time() for any string that begins with "eat" (case insensitive):
<?
var_dump(strtotime('10 September 2000')); # int(968569200)
var_dump(strtotime('10 September 2000 asdfasdfasdf'));# bool(false)
var_dump(strtotime('asdfasdfasdf 10 September 2000'));# bool(false)
var_dump(strtotime('eat')); # int(1220358823)
var_dump(strtotime('eat asdfasdfasdf')); # int(1220358823)
var_dump(strtotime('asdfasdf eat')); # bool(false)
?>
You'll notice that 'eat.*' will always be a valid timestamp, so just using strtotime($is_it_a_time) will return a false positive on "eat a sandwich"
25-Aug-2008 04:34
Uncommenting the default timezone in the php.ini file also seems to do the trick in getting rid of the error messages:
[Date]
; Defines the default timezone used by the date functions
date.timezone = America/New_York
22-Aug-2008 06:31
"5.1.0 Now issues the E_STRICT and E_NOTICE time zone errors."
This little footnote represents a failure mode under common conditions, which is extremely frustrating. For example, this code ALWAYS returns an error on PHP 5:
ini_set('error_reporting', E_ALL|E_STRICT);
echo strtotime('Sun, 20 Jul 2008 23:34:07 GMT', time());
Notice a standard HTTP-date was specified, so the PHP timezone setting will never affect the value returned by strtotime().
There is no documented workaround, and the suggested methods including date_default_timezone_get will cause the same errors. To make matters worse, those functions don't exist in older versions.
Based on my testing, it is necessary to provide PHP with a hard-coded timezone, any timezone at all, to prevent the error. Since the timezone has no affect on the results, I could use 'UTC' or 'America/Detroit' or any other valid string.
if (function_exists('date_default_timezone_set')) {
date_default_timezone_set('UTC');
}
echo strtotime('Sun, 20 Jul 2008 23:34:07 GMT', time());
This is the only solution I have found so far.
Enjoy
Robert Chapin
Chapin Information Services
21-Aug-2008 08:33
An easier way to find the first and last time stamp of any given month.
<?php
$dat = split(',',date('n,Y'));
$first = mktime(0,0,0,$dat[0],1,$dat[1]);
$last = mktime(23,59,59,$dat[0]+1,0,$dat[1]);
?>
12-Aug-2008 04:26
In response to Alex...
That is actually extremely useful. If noticed in your example it simply went backwards for "00". It took it as the previous month. This can be useful because you can simply subtract 1 to go backwards.
08-Aug-2008 03:48
strtotime() seems to treat dates delimited by slashes as m/d/y and dates delimited by dashes are treated as d-m-y.
print date('Y-m-d', strtotime("06/08/2008"));
returns 2008-06-08
while
print date('Y-m-d', strtotime("06-08-2008"));
returns 2008-08-06
Using PHP 5.2.6
23-Jul-2008 02:56
This function can be used to convert the timestamp generated by MySQL NOW() function into UNIX timestamp. Example:
Lets say MySQL NOW() returns '2008-07-23 06:07:42'.
<?php
$mysql_now='2008-07-23 06:07:42';
$time=strtotime($mysql_now);
echo date(d M y, H:i:s,$time);
//outputs: 23 Jul 08, 06:07:42
?>
Please note that the timestamp returned by mysql NOW() function may be the in the timezone of the server on which it was generated, and not always in GMT.
01-Jul-2008 09:48
It is worth noting, that strtotime() accepts ISO week date format (for example "2008-W27-2" is Tuesday of week 27 in 2008), so it can be easily used to get the date of a given week number.
<?php
function week($year, $week)
{
$from = date("Y-m-d", strtotime("{$year}-W{$week}-1")); //Returns the date of monday in week
$to = date("Y-m-d", strtotime("{$year}-W{$week}-7")); //Returns the date of sunday in week
return "Week {$week} in {$year} is from {$from} to {$to}.";
}
echo week(2008,27);
//Returns: Week 27 in 2008 is from 2008-06-30 to 2008-07-06.
?>
24-Jun-2008 09:59
When using a custom timestamp and adding a day to it, this works:
strtotime("20080601 +1 day")
this does not:
strtotime("20080601") + strtotime("+1 day")
that's because "+1 day" is another way to say the timestamp corresponding to tomorrow as of right now.
If you do it the wrong way, you'll end up with really bizarre dates in your loops. I was going from 20080601 to 19101019 to 19490412. What fun it was figuring that out. :)
19-Jun-2008 07:10
BEWARE: Someone thought this was a good idea...
$t = strtotime('2008-00-14'); // == 1197590400
$d = date("d-m-Y", $t); // == 14-12-2007
I am not sure when this function EVER returns false but its obviously not when the dates incorrect.
10-Jun-2008 05:31
When using DB2 as an ODBC database source, the timestamps returned are in format "YYYY-MM-DD HH:MM:SS.mmmmmm" (m being microseconds).
Given that strtotime($str) is only accurate down to the second, you need to remove the microseconds from the string for it to work in strtotime.
For example:
<?php
$date = "2008-06-10 16:15:50.123456"; //as returned by DB2 SQL
$date = substr($date, 0, 19); //chop off the last 7 characters
//thus
$date == 1213110950;
//and
date('Y-m-d H-i-s', $date) == "2008-06-10 16:15:50";
?>
Note that if you wish to preserve the microseconds, you will need to do so before you chop them off of the string, but you don't need to include them or even pad timestamps with zeros when inserting them back into DB2.
01-Jun-2008 04:56
Someone already reported an issue with finding the next month on the 31st of a month goes to two months down (essentially the next month with 31 days). There's a workaround for PHP 5.3+ here:
http://bugs.php.net/bug.php?id=44073
If you don't have 5.3 like me (and I can't update it) this code works:
<?php
// On the 31st of May:
strtotime("+1 month"); // Outputs July
strtotime("+1 month", strtotime(date("F") . "1")); // Outputs June
?>
In Engish: Figure out next month relative to the first of this month (date ("F") returns current month).
09-May-2008 09:08
Booyah! $time containing only numeric and space characters results in unexpected output (at least on Win2K server, not checked with linux).
<?php
echo date('d F Y', strtotime('2007')); // today's date (09 May 2008) displayed
echo date('d F Y', strtotime('01 2007')); // Warning: date(): Windows does not support dates prior to midnight (00:00:00), January 1, 1970
echo date('d F Y', strtotime('01 01 2007')); // same warning
echo date('d F Y', strtotime('01 Jan 2007')); // 01 January 2007
?>
No bug report submitted, I don't know enough about php and servers to know if this is expected behaviour or not.
27-Mar-2008 09:26
It suggests prior to v4.4, "next XXXday" is incorrectly calculated as "+2", and that a remedy is "+1".
"+1" will result in an incorrect date. The solution should actually read just enter "xxxday" as the offset - not "+1 xxxDay"
24-Feb-2008 03:22
The phrase "about any English textual datetime description" is misleading. The GNU Date Input Formats syntax is actually quite limited and, counterintuitively, some commonly used formats result in incorrect or invalid dates that confound users. In particular, the commonly used m-d-y format does not work. 2-23-08 is invalid!
It would be helpful to list the allowed date formats in the documentation rather than just by reference to the GNU docs:
for numeric months the only valid formats are:
y-m-d
m/d/y
m/d
for text months the only valid formats are:
d month y
d month
month d y
d-month-y
month d
Although the GNU doc says leading zeros are required for numbers less than 10 this does not seem to be necessary (5/7/8 is same as 05/07/08).
31-Jan-2008 10:15
I found some different behaviors between PHP 4 and PHP 5. I have tested this on just two versions: PHP Version 5.2.3-1ubuntu6.3 and PHP Version 4.3.10-22.
Example 1:
<?php
$ts2 = strtotime("1st Thursday", $ts1)
var_dump($ts2)
// this works in PHP 4
// PHP 5 dumps bool(false)
?>
Example 2:
<?php
$ts2 = strtotime("first Thursday", $ts1)
var_dump($ts2)
// this works in PHP 4
// also works in PHP 5
?>
21-Jan-2008 02:56
As with each of the time-related functions, and as mentioned in the time() notes, strtotime() is affected by the year 2038 bug on 32-bit systems:
<?php
echo strtotime('13 Dec 1901 20:45:51'); // false
echo strtotime('13 Dec 1901 20:45:52'); // -2147483648
echo strtotime('19 Jan 2038 03:14:07'); // 2147483647
echo strtotime('19 Jan 2038 03:14:08'); // false
?>
10-Dec-2007 05:21
Be careful with spaces between the "-" and the number in the argument, for some PHP-installations...
<?php
strtotime("- 1 day") // ...with space - will ADD a day
strtotime("-1 day") // ...works perfect
?>
05-Dec-2007 07:42
Here is a list of differences between PHP 4 and PHP 5 that I have found
(specifically PHP 4.4.2 and PHP 5.2.3).
<?php
$ts_from_nothing = strtotime();
var_dump($ts_from_nothing);
// PHP 5
// bool(false)
// WARNING: Wrong parameter count...
// PHP 4
// NULL
// WARNING: Wrong parameter count...
// remember that unassigned variables evaluate to NULL
$ts_from_null = strtotime($null);
var_dump($ts_from_null)...
// PHP 5
// bool(false)
// throws a NOTICE: Undefined variable
// PHP 4
// current time
// NOTICE: Undefined variable $null...
// NOTICE: Called with empty time parameter...
$ts_from_empty = strtotime("");
var_dump($ts_from_empty);
// PHP 5
// bool(false)
// PHP 4
// current time
// NOTICE: Called with empty time parameter
$ts_from_bogus = strtotime("not a date");
var_dump($ts_from_bogus);
// PHP 5
// bool(false)
// PHP 4
// -1
?>
05-Dec-2007 02:35
I get what appear to be incorrect results from
<?php
//$yr=4-digit year
strtotime($yr);
?>
a) for $yr from 1960-1999, function returns timestamp of current date/time in $yr
b) for other $yr from xx60-xx99, function returns false as expected.
c) for $yr from xx00-xx59, function returns current timestamp.
25-Nov-2007 10:38
As for the cases which Beat notes as "CORRECT": 23:59:59 30 September is less than an hour earlier than 00:00:00 1 October - and by happenstance Central European Time, the time zone that Beat is using locally, is one hour ahead of UTC.
So 23:59:59 30 September UTC corresponds to 00:59:59 1 October CET, and by ignoring the time and timezone information you just happen to get the "correct" result.
23-Nov-2007 06:00
Beat's analysis fails to take into account the fact that when strtotime() subtracts three months it really does subtract three months: 31 December minus three months is 31 September. And a look at the calendar will show what "31 September" is really called.
In other words strtotime() is doing exactly what Beat claims in the following note mktime() does.
The reason why Beat's "workaround" works is because
mktime( 23, 59, 59, 1 - 3, 0, 2008 );
represents the 0th day of the -2nd month of 2008. That's 0 October 2007. And 0 October is 30 September.
Which is the reason Beat clearly discovered that using mktime( 23, 59, 59, 12 - 3, 31, 2007 ) to represent 31 December 2007 turned out not to work.
mktime(23, 59, 59, 12, 31, 2007) == mktime(23, 59, 59, 1, 0, 2008) but
mktime(23, 59, 59, 12-3, 31, 2007) refers to "31 September 2007", --> "1 October 2007"; and
mktime(23, 59, 59, 1-3, 0, 2008) refers to "0 '-2' 2008" --> "0 October 2007" --> "30 September 2007".
Just because the date you're starting from happens to be the last day of the month, it doesn't mean that subtracting a month will leave you at the last day of the previous month.
16-Nov-2007 01:44
I had a whole bunch of trouble with a calendar where I was trying to create recurring events. The problem was that for certain dates, the 'second friday' of the month would work and would not. There are a lot of flaws with the way I was processing, so I wrote this instead of using strtotime() to solve my issue.
This solves the simple problem of finding the x weekday of any month. (first friday of 11-2007 or last tuesday of Dec, 1962)
<?php
function get_day( $describer, $weekday, $reference_date ) { //$reference_date format = m-Y
$d = explode('-',$reference_date);
switch ($describer) {
case 'first': $offset = get_day_offset($reference_date, $weekday); break;
case 'second': $offset = get_day_offset($reference_date, $weekday) + 7; break;
case 'third': $offset = get_day_offset($reference_date, $weekday) + 14; break;
case 'fourth': $offset = get_day_offset($reference_date, $weekday) + 21; break;
case 'last': $reference_date = ($d[0]+1).'-'.($d[1]); $d = explode('-',$reference_date);
$offset = get_day_offset($reference_date, $weekday) - 7; break;
}
$r = mktime( 0, 0, 0, $d[0], 1+$offset, $d[1] );
return $r; //returns timestamp format
}
function get_day_offset( $anchor , $target ) { //$anchor format = m-Y
$ts = explode('-',$anchor);
$ts = mktime(0,0,0,$ts[0],'01',$ts[1]);
$anchor = date("w",$ts);
$target = strtolower($target);
$days = array( 'sunday'=>0, 'monday'=>1, 'tuesday'=>2, 'wednesday'=>3, 'thursday'=>4, 'friday'=>5, 'saturday'=>6 );
$offset = $days[$target] - $anchor;
if ($offset<0) $offset+=7;
return $offset; //returns 0-6 for use in get_day();
}
$date1 = get_day("second", "saturday", "12-2007");
$date2 = get_day("last", "friday", "11-2007");
echo "Second Saturday of December, 2007: ".date("m-d-Y", $date1)."<br>";
echo "Last Friday of November, 2007: ".date("m-d-Y", $date2)."<br>";
?>
Outputs:
Second Saturday of December, 2007: 12-08-2007
Last Friday of November, 2007: 11-30-2007
15-Nov-2007 10:53
Not sure why the ordinals are not on this page.
However I was trying to subtract some hours from a certain date.
echo date('m-d-Y', strtotime("- x hours"));
This code would not work. Instead it would add two hours.
You must use the ordinal ago.
echo date('m-d-Y', strtotime("x hours ago"));
Will return the right date.
Here are the ordinals.
Relative and Ordinal Specifiers:
ago: past time relative to now; such as "24 hours ago"
tomorrow: 24 hours later than the current date and time
yesterday: 24 hours earlier than the current date and time
today: the current date and time
now: the current date and time
last: modifier meaning "the preceding"; for example, "last tuesday"
this: the given time during the current day or the next occurrence of the given time; for example, "this 7am" gives the timestamp for 07:00 on the current day, while "this week" gives the timestamp for one week from the current time
next: modifier meaning the current time value of the subject plus one; for example, "next hour"
first: ordinal modifier, esp. for months; for example, "May first" (actually, it's just the same asnext)
third: see first (note that there is no "second" for ordinality, since that would conflict with thesecond time value)
fourth: see first
fifth: see first
sixth: see first
seventh: see first
eighth: see first
ninth: see first
tenth: see first
eleventh: see first
twelfth: see first
06-Nov-2007 10:50
strtotime() reads the timestamp in en_US format if you want to change the date format with this number, you should previously know the format of the date you are trying to parse. Let's say you want to do this :
strftime("%Y-%m-%d",strtotime("05/11/2007"));
It will understand the date as 11th of may 2007, and not 5th of november 2007. In this case I would use:
$date = explode("/","05/11/2007");
strftime("%Y-%m-%d",mktime(0,0,0,$date[1],$date[0],$date[2]));
Much reliable but you must know the date format before. You can use javascript to mask the date field and, if you have a calendar in your page, everything is done.
Thank you.
02-Oct-2007 12: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
?>
01-Oct-2007 10: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
?>
14-Sep-2007 11: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.
03-Sep-2007 04: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.
28-Aug-2007 02: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.
16-Aug-2007 04: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.
26-Jul-2007 06: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
19-Jul-2007 03: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.
07-Jul-2007 07: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).
<?php
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...
01-Jul-2007 04: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.
01-Jun-2007 05: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....
13-May-2007 05: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.
08-Apr-2007 03: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.
<?php
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:
<?php
$Date = "04-07-2007";
$Days = conv_to_xls_date($Date);
?>
$Days will contain 39179
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');
?>
]
09-Feb-2007 09: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).
16-Jan-2007 11: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");
05-Oct-2006 09: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.
11-May-2006 12:18
The GNU manual page has moved, the new address is
http://www.gnu.org/software/shishi/manual/html_node/Date-input-formats.html
11-Apr-2006 01: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);
24-Jan-2006 07: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".)
18-Jan-2006 01: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.
11-Jan-2006 05: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
06-Oct-2005 11:34
Note strtotime() in PHP 4 does not support fractional seconds.
See http://bugs.php.net/bug.php?id=28717 especially if you happen to swap to ODBC for MS SQL Server and wonder what's happened!
28-Sep-2005 05:55
The PHP 5.1.0 change is a major backward compatibility break.
Now, that the returned value on failure has changed, the correct way to detect problems on all PHP versions is:
<?php
if (($time = strtotime($date)) == -1 || $time === false) {
die 'Invalid date';
}
?>
[red (derick): note, this is not 100% correct, as in this case 1969-12-31 23:59 will be thrown out as that timestamp is "-1"]
29-Aug-2005 03:25
One behavior to be aware of is that if you have "/" in the date then strtotime will believe the last number is the year, while if you use a "-" then the first number is the year.
12/4/03 will be evaluated to the same time as 03-12-4.
This is in the gnu documentation linked to in the article. I confirmed the behavior with strtotime and getdate.
Steve Holland
15-Aug-2005 08:49
When using multiple negative relative items, the result might be a bit unexpected:
<?php
$basedate = strtotime("15 Aug 2005 10:15:00");
$date1 = strtotime("-1 day 2 hours", $basedate);
$date2 = strtotime("-1 day -2 hours", $basedate);
echo date("j M Y H:i:s", $date1); // 14 Aug 2005 12:15:00
echo date("j M Y H:i:s", $date2); // 14 Aug 2005 08:15:00
?>
The minus sign has to be added to every relative item, otherwise they are interpreted as positive (increase in time). Other possibility is to use "1 day 2 hours ago".
15-Jul-2005 11:21
Maybe it saves others from troubles:
if you create a date (i.e. a certain day, like 30.03.2005, for a calendar for example) for which you do not consider the time, when using mktime be sure to set the time of the day to noon:
<?php
$iTimeStamp = mktime(12, 0, 0, $iMonth, $iDay, $iYear);
?>
Otherwhise
<?php
// For example
strtotime('-1 month', $iTimeStamp);
?>
will cause troubles when calculating the relative time. It often is one day or even one month off... After I set the time to noon "strtotime" calculates as expected.
Cheers
Denis
13-Jul-2005 01:13
relative dates..
<?php
echo date('d F Y', strtotime('last monday', strtotime('15 July 2005'))); // 11th
echo "<br>";
echo date('d F Y', strtotime('this monday', strtotime('15 July 2005'))); // 18th
echo "<br>";
echo date('d F Y', strtotime('next monday', strtotime('15 July 2005'))); // 25th
?>
28-Jun-2005 02:14
This is an easy way to calculate the number of months between 2 dates (including the months in which the dates are themselves).
<?php
$startDate = mktime(0,0,0, 6, 15, 2005);
$stopDate = mktime(0,0,0, 10, 8, 2006);
$nrmonths = ((idate('Y', $stopDate) * 12) + idate('m', $stopDate)) - ((idate('Y', $startDate) * 12) + idate('m', $startDate));
?>
Results in $nrmonths = 16.
09-May-2005 10:49
Here's a quick one-line function you can use to get the time difference for relative times. But default, if you put in a relative time (like "1 minute"), you get that relative to the current time. Using this function will give you just the time difference in seconds:
<?php function relative_time( $input ) { return strtotime($input) - time(); } ?>
For example "1 minute" will return 60, while "30 seconds ago" will return -30
Valid relative time formats can be found at http://www.gnu.org/software/tar/manual/html_chapter/tar_7.html#SEC115
22-Apr-2005 06:59
If you strtotime the epoch (Jan 1 1970 00:00:00) you will usually get a value, rather than the expected 0. So for example, if you were to try to use the epoch to calculate the difference in times (strtotime(Jan 1 1970 21:00:00)-strtotime(Jan 1 1970 20:00:00) for example) You get a value that depends strongly upon your timezone. If you are in EST for example, the epoch is actually shifted -5 to YOUR epoch is Jan 1 1970 19:00:00) In order to get the offset, simply use the following call to report the number of seconds you are away from the unix epoch. $offset=strtotime("1970-01-01 00:00:00"); Additionally, you can append GMT at the end of your strtotime calls so save yourself the trouble of converting relative to timezone.
I ran into the same problem with "last" as gabrielu at hotmail dot com (05-Apr-2005 10:45) when using strtotime() with getdate(). My only guess is that it has to do with daylight savings time as it seemed to be ok for most dates except those near the first Sunday in April and last Sunday in October.
I used strftime() with strtotime() and that gave me the result I was looking for.
05-Apr-2005 06:45
While working on an employee schedule application I noticed an issue with using strtotime('last...'). I ran tests on each weekday for each week within a year and noticed inconsistencies while using:
date('m/d/Y', strtotime('last Wednesday', '2005-04-05'))
Most calculations of the 'last Wednesday' for each week calculated accordingly however I noticed a problem with several dates, one being '04/05/2005' (April 5th 2005).
date('m/d/Y', strtotime('last Wednesday', '2005-04-05'))
The above should have returned '03/30/2005'. Instead, it returned '03/29/2005'. I don't understand why the function is returning this value. Regardless, my solution:
date('m/d/Y', strtotime('-1 week' ,strtotime('Wednesday', '2005-04-05')))
09-Dec-2004 05:12
Be warned that strtotime() tries to "guess what you meant" and will successfully parse dates that would otherwise be considered invalid:
<?php
$ts = strtotime('1999-11-40');
echo date('Y-m-d', $ts);
// outputs: 1999-12-10
?>
It is my understanding (I have not verified) that the lexer for strtotime() has been rewritten for PHP5, so these semantics may only apply for PHP4 and below.
20-Aug-2004 03:38
After a slight moment of frustration, and finding that I'm not the only one with this problem (see http://bugs.php.net/bug.php?id=28088 - it's a known bug) I decided to write a short workaround for dealing with the 00 hour problem.
The problem only seems to occur when inputting strings such as '08/20/2004 0047' and NOT '08/20/2004 00:47'. Hence, my fix:
<?php
$your_value ( preg_replace ('#^(\d+/\d+/?\d{2,4} )(00)(\d{2})$#', '$1$2:$3', $your_value() ));
?>
06-Apr-2004 08:39
I neglected to include the solution in my last post for using strtotime() with date-time data stored in GMT. Append the string "GMT" to all of your datetimes pulled from MySQL or other database that store date-times in the format "yyyy-mm-dd hh:ii:ss" just prior to converting them to a unix timestamp with strtotime(). This will ensure you get a valid GMT result for times during daylight savings.
EXAMPLE:
<?php
$date_time1 = strtotime("2004-04-04 02:00:00"); // returns bad value -1 due to DST
$date_time2 = strtotime("2004-04-04 02:00:00 GMT"); // works great!
?>
02-Jan-2004 12:24
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.
