downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

time> <strptime
[edit] Last updated: Fri, 22 Jul 2011

view this page in

strtotime

(PHP 4, PHP 5)

strtotimeParse about any English textual datetime description into a Unix timestamp

Description

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

The function expects to be given a string containing an English date format and will try to parse that format into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 UTC), relative to the timestamp given in now, or the current time if now is not supplied.

This function will use the TZ environment variable (if available) to calculate the timestamp. Since PHP 5.1.0 there are easier ways to define the timezone that is used across all date/time functions. That process is explained in the date_default_timezone_get() function page.

Parameters

time

A date/time string. Valid formats are explained in Date and Time Formats.

now

The timestamp which is used as a base for the calculation of relative dates.

Return Values

Returns a timestamp on success, FALSE otherwise. Previous to PHP 5.1.0, this function would return -1 on failure.

Errors/Exceptions

Every call to a date/time function will generate a E_NOTICE if the time zone is not valid, and/or a E_STRICT or E_WARNING message if using the system settings or the TZ environment variable. See also date_default_timezone_set()

Changelog

Version Description
5.3.0 Prior to PHP 5.3.0, 24:00 was not a valid format and strtotime() returned FALSE.
5.2.7 In PHP 5 prior to 5.2.7, requesting a given occurrence of a given weekday in a month where that weekday was the first day of the month would incorrectly add one week to the returned timestamp. This has been corrected in 5.2.7 and later versions.
5.1.0 Now returns FALSE on failure, instead of -1.
5.1.0

Now issues the E_STRICT and E_NOTICE time zone errors.

5.0.2 In PHP 5 up to 5.0.2, "now" and other relative times are wrongly computed from today's midnight. This differs from other versions where it is correctly computed from current time.
5.0.0 Microseconds began to be allowed, but they are ignored.
4.4.0 In PHP versions prior to 4.4.0, "next" is incorrectly computed as +2. A typical solution to this is to use "+1".

Examples

Example #1 A strtotime() example

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

Example #2 Checking for failure

<?php
$str 
'Not Good';

// previous to PHP 5.1.0 you would compare with -1, instead of false
if (($timestamp strtotime($str)) === false) {
    echo 
"The string ($str) is bogus";
} else {
    echo 
"$str == " date('l dS \o\f F Y h:i:s A'$timestamp);
}
?>

Notes

Note:

If the number of the year is specified in a two digit format, the values between 00-69 are mapped to 2000-2069 and 70-99 to 1970-1999. See the notes below for possible differences on 32bit systems (possible dates might end on 2038-01-19 03:14:07).

Note:

The valid range of a timestamp is typically from Fri, 13 Dec 1901 20:45:54 UTC to Tue, 19 Jan 2038 03:14:07 UTC. (These are the dates that correspond to the minimum and maximum values for a 32-bit signed integer.) Additionally, not all platforms support negative timestamps, therefore your date range may be limited to no earlier than the Unix epoch. This means that e.g. dates prior to Jan 1, 1970 will not work on Windows, some Linux distributions, and a few other operating systems. PHP 5.1.0 and newer versions overcome this limitation though.

For 64-bit versions of PHP, the valid range of a timestamp is effectively infinite, as 64 bits can represent approximately 293 billion years in either direction.

Note:

Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: 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.

To avoid potential ambiguity, it's best to use ISO 8601 (YYYY-MM-DD) dates or DateTime::createFromFormat() when possible.

See Also



time> <strptime
[edit] Last updated: Fri, 22 Jul 2011
 
add a note add a note User Contributed Notes strtotime
ei7024 at wayne dot edu 25-Jul-2011 01:57
This is the solution to the problems with date below 1970. Below code help the date to show up in format such as MM/DD/YYYY. It can be tailored to fit any format.

This works if the database stores the dates in "DATE" format.

<?php

$query
= "SELECT emp_fn,emp_ln, emp_dob FROM requests WHERE id=$id;";
$result = mysql_query($query,$DBConn);
$row = mysql_fetch_array($result);

//TESTING BELOW 1970 Date of Birth

$dobcheck = strtotime($row['emp_dob']);

//NOTE: echo $dobcheck on your system to see if you get negative values for date below 1970

if ($dobcheck <= 0)
    {
       
$date = $row['emp_dob'];
       
$date = explode('-', $date);
       
$Y = $date[0];
       
$M = $date[1];
       
$D = $date[2];
       
$dobshow = $M."/".$D."/".$Y;        //echos mm/dd/YYYY format for dates below 1970.
   
} else {
       
$dobshow = date("m/d/Y",strtotime($row['emp_dob']));   
    }

//ENDTESTING

?>
lazzich 15-Jul-2011 01:09
Calculate the time that past since an event happened:

<?php
function time_ago($date,$time) {
 
$days = abs(ceil((strtotime($date)-strtotime("now"))/86400));
    if (
$days > 0$timepast = $days." days";
    if (
$days == 1$timepast = $days." day";
 
$hours = abs(ceil((strtotime($time)-strtotime("now"))/3600));
    if (
$days == 0) $timepast = "about ".$hours." hours";
    if (
$hours == 1) $timepast = "about ".$hours." hour";
 
$minutes = abs(ceil((strtotime($time)-strtotime("now"))/60))-($hours*60);
    if (
$hours == 0) $timepast = $minutes." minutes";
    if (
$minutes == 1) $timepast = $minutes." minute";
  return
$timepast;
}

$date('2011/07/15');
$time('15:00:00');
echo
time_ago($date,$time);

?>
Annomoys 11-Jun-2011 10:43
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)

}

?>
Ayumi Yu 07-May-2011 10:33
Using PHP 5.3.2-1ubuntu4.7, I observed some strangeness with strtotime, it seemed to misinterpret dates with periods:

$formatted = date( 'Y-m-d H:i:s', strtotime($anyFormat) );

This would sometimes return '1970-01-01 00:00:00' (timestamp of 0), or the current day with different times attached. The dates were being misinterpreted as times, which are accepted in the format of ( 't'? HH [.:] MM [.:] II ), and the date was assumed to be the current date. In other cases when the times were invalid (e.g. in 2010.03.01, HH = 2010 > 24), I got a timestamp of 0.

Fix: Replace dots with slashes, then call date with that.

$fixedAnyFormat = str_replace( '.', '/', $anyFormat );
usrhlp 03-May-2011 04:20
When trying the following code

<?php echo("date("l jS \o\f F Y",strtotime("2011-05-01"))"); ?>

i was getting the output

"Tuesday 3rd o May 2011".

I found that in order to get the word "of" i needed to double escape the f so i used this code instead which works.

<?php echo("date("l jS \o\\f F Y",strtotime("2011-05-01"))"); ?>
peterson at npd dot ufsc dot br 08-Apr-2011 08:38
A function to add two times, without using the explode function

<?php

$hour_one
= "01:20:20";
$hour_two = "05:50:20";
$h strtotime($hour_one);
$h2 = strtotime($hour_two);

$minute = date("i", $h2);
$second = date("s", $h2);
$hour = date("H", $h2);

echo
"<br>";

$convert = strtotime("+$minute minutes", $h);
$convert = strtotime("+$second seconds", $convert);
$convert = strtotime("+$hour hours", $convert);
$new_time = date('H:i:s', $convert);

echo
$new_time;

?>
Anonymous 01-Mar-2011 04:17
PHP strtotime() does not handle the ISO8601 notation for "duration."  This handles the most likely subset of the duration standard (the one that is used by eBay).
<?php // RAY_duration_strtotime.php
error_reporting(E_ALL);
date_default_timezone_set('America/New_York');

// WHAT DOES THIS STRING MEAN?
$str = 'P1Y3M2DT16H2M40S';

// IT IS THE ISO8601 FORMAT FOR A DURATION.
// SEE http://en.wikipedia.org/wiki/ISO_8601

// IT MEANS THIS:
// P   = Pending (INDICATOR OF ISO8601 DURATION)
// 1Y  = 1 Year
// 3M  = 3 Months
// 2D  = Two Days
// T   = Time Separator (M is ambiguous)
// 16H = Sixteen hours
// 2M  = Two minutes
// 40S = Forty seconds

// STRTOTIME CANNOT HANDLE ISO-8601 DURATIONS
$dur = strtotime($str);
var_dump($dur);
echo
"<br/>";

// GET THE DURATION IN SECONDS FOR USE IN ARITHMETIC
$dur = duration_strtotime($str);
echo
"<br/>" . number_format($dur) . ' SECONDS';

// USE THE DURATION IN ARITHMETIC
echo "<br/>" . date('r', strtotime("NOW + $dur SECONDS"));

// A FUNCTION TO MAKE A DURATION STRING INTO A NUMBER OF SECONDS
function duration_strtotime($str, $sho=FALSE)
{
   
// REMOVE THE AMBIGUITY OF MONTH AND MINUTE -- MAKE MONTH = X
   
$arr = explode('T', $str);
   
$arr[0] = str_replace('M', 'X', $arr[0]);
   
$new = implode('T', $arr);

   
// EXPAND THE STRING INTO SOMETHING SENSIBLE
   
$new = str_replace('S', 'seconds ', $new);
   
$new = str_replace('M', 'minutes ', $new);
   
$new = str_replace('H', 'hours ',   $new);
   
$new = str_replace('T', ' ',        $new);
   
$new = str_replace('D', 'days',     $new);
   
$new = str_replace('X', 'months '$new);
   
$new = str_replace('Y', 'years ',   $new);
   
$new = str_replace('P', NULL,       $new);

    if (
$sho) var_dump($new);

   
// RETURN THE NUMBER OF SECONDS IN THE DURATION
   
return strtotime($new) - strtotime('NOW');
}
?>
adarsh at freedomsites dot co dot uk 28-Feb-2011 01:46
Function to add duration to time

<?php
function addTime($start_time, $duration)    {
    list(
$dhrs, $dmin, $dsec)    = explode(':',$duration);
    return
date('H:i:s', strtotime($start_time.' '.'+'.$dhrs.' hours,'. $dmin.' minutes,' .$dsec. ' seconds'));
}
?>
a dot fruchi at bit-runners dot com 17-Feb-2011 01:45
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'

?>
nick at optixsolutions dot co dot uk 10-Feb-2011 05:36
Function to add days (excluding specified days/dates)

<?php
function addDays($timestamp, $days, $skipdays=NULL, $skipdates=NULL){
   
// $skipdays: array (Monday-Sunday) eg. array("Saturday","Sunday")
    // $skipdates: array (YYYY-mm-dd) eg. array("2012-05-02","2015-08-01");
   
$i = 1;
   
    while(
$days >= $i){
       
$timestamp = strtotime("+1 day" ,$timestamp);
        if(
in_array(date("l",$timestamp), $skipdays) || in_array(date("Y-m-d",$timestamp), $skipdates)){
           
$days++;
        }
       
$i++;
    }
   
    return
$timestamp;
}
?>

I use this in combination with the calculateBankHolidays function in the notes here: http://php.net/manual/en/ref.calendar.php to skip working days in the UK:

<?php
$skipdays
= array("Saturday","Sunday");
$skipdates = array_merge(calculateBankHolidays(date("Y")), calculateBankHolidays(date("Y", strtotime("+1 year"))));

$ts = addDays(strtotime("now"), 1, $skipdays, $skipdates);
?>
nyctimus at yahoo dot com 06-Jan-2011 01:54
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.
x at xero dot nu 21-Dec-2010 05:41
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;
?>
ash at itsash dot co dot uk 05-Nov-2010 05:24
I find myself using strtotime() 90% of the time when working with date formats. However there are times when strtotime() doesn't work how I want it to. I have created a DateTime class which contains a couple of useful methods feel free to use it.

Please remember as of PHP 5. there is a standard class called "DateTime", thus why my class is called PHPDateTime and it just simply extends PHP's DateTime class with some public static methods.

If you are not using php 5, just replce "final class PHPDateTime extends DateTime" with "final class DateTime". I assume you all know the double colon scope? for those whom don't it's simply.

<?php
// this will give us 2010-02-28 ()
echo PHPDateTime::DateNextMonth(strftime('%F', strtotime("2010-01-31 00:00:00")), 31);
?>

The class is as follows....

<?php
/**
 * IA FrameWork
 * @package: Classes & Object Oriented Programming
 * @subpackage: Date & Time Manipulation
 * @author: ItsAsh <ash at itsash dot co dot uk>
 */

final class PHPDateTime extends DateTime {

   
// Public Methods
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
   
    /**
     * Calculate time difference between two dates
     * ...
     */
   
   
public static function TimeDifference($date1, $date2)
       
$date1 = is_int($date1) ? $date1 : strtotime($date1);
       
$date2 = is_int($date2) ? $date2 : strtotime($date2);
       
        if ((
$date1 !== false) && ($date2 !== false)) {
            if (
$date2 >= $date1) {
               
$diff = ($date2 - $date1);
               
                if (
$days = intval((floor($diff / 86400))))
                   
$diff %= 86400;
                if (
$hours = intval((floor($diff / 3600))))
                   
$diff %= 3600;
                if (
$minutes = intval((floor($diff / 60))))
                   
$diff %= 60;
               
                return array(
$days, $hours, $minutes, intval($diff));
            }
        }
       
        return
false;
    }
   
   
/**
     * Formatted time difference between two dates
     *
     * ...
     */
   
   
public static function StringTimeDifference($date1, $date2) {
       
$i = array();
        list(
$d, $h, $m, $s) = (array) self::TimeDifference($date1, $date2);
       
        if (
$d > 0)
           
$i[] = sprintf('%d Days', $d);
        if (
$h > 0)
           
$i[] = sprintf('%d Hours', $h);
        if ((
$d == 0) && ($m > 0))
           
$i[] = sprintf('%d Minutes', $m);
        if ((
$h == 0) && ($s > 0))
           
$i[] = sprintf('%d Seconds', $s);
       
        return
count($i) ? implode(' ', $i) : 'Just Now';
    }
   
   
/**
     * Calculate the date next month
     *
     * ...
     */
   
   
public static function DateNextMonth($now, $date = 0) {
       
$mdate = array(0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
        list(
$y, $m, $d) = explode('-', (is_int($now) ? strftime('%F', $now) : $now));
       
        if (
$date)
           
$d = $date;
       
        if (++
$m == 2)
           
$d = (($y % 4) === 0) ? (($d <= 29) ? $d : 29) : (($d <= 28) ? $d : 28);
        else
           
$d = ($d <= $mdate[$m]) ? $d : $mdate[$m];
       
        return
strftime('%F', mktime(0, 0, 0, $m, $d, $y));
    }
   
}
?>
marcodemaio at vanylla dot it 27-Oct-2010 06:09
NOTE: strttotime returns wrong values (or guessed values) when the Week day does not macth 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 strtime, 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);
?>
Nolan Grupe 29-Sep-2010 07:53
If you're trying to make Saturday (or any other day for that matter) the first day of the week to select datasets,  here's a good workaround:

<?php
$last_sat
=date("z", strtotime("last Saturday"));
$second_last_sat=date("z", strtotime("last Saturday-1 week"));
?>

then just query your database like so:

select everything since last saturday:
SELECT whatever.whatever from wherever WHERE DAYOFYEAR(complete) <= DAYOFYEAR(CURDATE()) AND DAYOFYEAR(complete) > ".$last_sat."

the week before (beginning on a saturday):
SELECT whatever.whatever from wherever WHERE  DAYOFYEAR(complete) <= ".$last_sat." AND DAYOFYEAR(complete) > ".$second_last_sat."

Good luck!
sam at frontiermedia dot net dot au 28-Sep-2010 10:23
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!
Tim 19-Sep-2010 04:52
Unlike "yesterday 14:00", "14:00 yesterday" will return 00:00 of yesterday.  Here's a function that'll fix that:

<?php
function fix_strtotime($date)
{
    if(
preg_match('/([012]?[0-9]?:[0-5]{1}\d\s*[aA|pP]?[mM]?)(\s+)(.+)/', $date, $matches))
    {
        return
strtotime($matches[3] . $matches[2] . $matches[1]);
    }
    return
strtotime($date);
}
echo
date('Y-m-d H:i:s', fix_strtotime('14:00 yesterday')); // 2010-09-17 14:00:00
echo date('Y-m-d H:i:s', fix_strtotime('yesterday 14:00')); // 2010-09-17 14:00:00
?>
jerramw at gmail dot com 26-Aug-2010 04:32
One liner to get end of financial year (EFY)

<?php
$efy
= ($efy = mktime(0,0,0,7,1,date('Y'))) > time() ? --$efy:strtotime('+1 year', --$efy);

echo
date('d/m/y H:i:s',$efy);
// 30/06/11 23:59:59
?>

I use 1 July as the test date, so it should work if you run it at say 11.59pm June 30. Should be right, ymmv.
jamon at clearsightdesign dot com 10-Aug-2010 07:42
Here's a PHP function to find the next valid weekday. Modify as necessary for your needs.

- Jamon Holmgren

<?php
   
/**
     *    next_weekday() - finds the next valid weekday given a timestamp.
     *    $next_weekday = valid_weekday($timestamp);
     *   
     *    By Jamon Holmgren.
     *   
     *    @return int
     */
   
function next_weekday($timestamp = NULL) {
        if(
$timestamp === NULL) $timestamp = time();
       
$next = strtotime("midnight +1 day", $timestamp);
       
$d = getdate($next);
        if(
$d['wday'] == 0 || $d['wday'] == 6) $next = strtotime("midnight next monday", $timestamp);
        return
$next;
    }
?>
Stefan Kunstmann 30-Jul-2010 01:32
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'));
?>
jim dot leek at eng dot ox dot ac dot uk 19-Jul-2010 11:20
Don't be tempted to use strtotime to compare dates:

e.g.

<?php
   
// Calculate the difference in days. 
   
$date1 = strtotime(2010-10-10);
   
$date2 = strtotime(2011-12-01);
   
$daysDiff = ($date2 - $date1)/(24 * 60 * 60);

   
// Which is the latest?
   
if ($date2 > $date1) {
      echo
"$date2 is later than $date1";
    }
?>

If you do, your code will be susceptible to the 2038 bug.

(This is because Unix timestamps cannot deal with dates before Fri, 13 Dec 1901 20:45:54 UTC and after Tue, 19 Jan 2038 03:14:07 UTC).

Instead convert your dates to Julian dates, and compare those. (For example use the function GregorianToJD which has been available since PHP4).
prajo74 at gmail dot com 13-Jul-2010 03:59
Take Care: strtotime() may not add months properly. The out put may not be as expected.

<?php echo '<br />'.date("Y-m-d", strtotime('+1 month', mktime(0,0,0,1,31,2010))); ?>

PHP Output - 2010-03-03 (Version 5.3.2) (Not Expected)

MySQL Output while adding 1 month to 2010-01-31 will be 2010-02-28 (As Expeced)
erjiang at indiana dot edu 09-Jul-2010 07:42
Be careful when parsing years.  If you pass a 4-digit number to strtotime, it will first try to interpret it as a time of day.  If it's an invalid time of day, it will interpret it as a year.

For example:

"0" through "999" => Unix epoch
"1000" => Today, 10:00:00
"1959" => Today, 19:59:00
"1960" => Today's month, day, and time in the year 1960

Tested on PHP 5.2.10
ceo at l-i-e dot com 17-Jun-2010 06:59
Apparently, somebody has decided that US-centric dates use '/' as separator, while Euro-centric use '-'.

Compare output of:
<?php
echo date('F d Y', strtotime('5-1-2010'));
echo
date('F d Y', strtotime('5/1/2010'));
?>
xanderl 11-May-2010 08:27
A Quick reference of accepted input:

Numeric steps (+1, -1 ...)
Numeric date/time (Y-m-d, H:i:s)
Ordinal names / numbers [first - twelfth = 1 - 12] *
Special ordinal name / numbers (last = -1, this = 0, next = 1)
Special words (tomorrow, yesterday, ago, fortnight, now, today, day, week, month, year, hour, minute, min, second, sec) **
Days / months [sunday - saterday, sun - sat, January - December, Jan - Dec]
Timezones (TZ="...")

* second is reserved for seconds in time notation, therefore is not allowed here
** plurals are also allowed by adding an 's'
support at esoweb dot eu 06-May-2010 03:47
This an example of recurrence days.

This function return a recurrence day per week during a period.
Exemple: All Thurday starting from 06 May 2010 during 52 weeks.

<?php
//function
function nextWeeksDay($date_begin,$nbrweek)
{
$nextweek=array();
for(
$i = 1; $i <= $nbrweek; $i++)  { // 52 week in one year of course
$nextweek[$i]=date('D d M Y', strtotime('+'.$i.' week',$date_begin));
}
return
$nextweek;
}
/// end function
/// example of a select date
// var
$date_begin = strtotime('06-05-2010'); //D Day Month Year  - like function format.
$nbrweek=52;
// call function
$result=nextWeeksDay($date_begin,$nbrweek);
// Preview
for($i = 1; $i <= $nbrweek; $i++)  {
echo
'<br> - '.$result[$i];
}
?>
A dot Lepe dev+php at alepe dot com 26-Apr-2010 03:11
This is a quick function to calculate the "working days" within a period of one year. "Working days" are those without weekends and without the holidays specified in the $holiday array. I left for the reader its implementation for more than 1 year.
<?php
/*
 * Author: Alberto Lepe
 * Calculates the working days from today to an specific date.
 * NOTE: counting starts from today
 * @pararm to_date: timestamp
 */
function get_working_days($to_date) {
   
$holidays = array(
       
1 => array(10), //2011 ...
       
2 => array(11),
       
3 => array(21), //... 2011
       
4 => array(29,30), //2010 ...
       
5 => array(3,4,5),
       
6 => array(),
       
7 => array(19),
       
8 => array(11,12,13),
       
9 => array(20,23),
      
10 => array(11),
      
11 => array(3,23),
      
12 => array(23) //... 2010
   
);

    for(
$to_date, $w = 0, $i = 0, $x = time(); $x < $to_date; $i++, $x = strtotime("+$i day")) {
       if(
date("N",$x) < 6 &! in_array(date("j",$x),$holidays[date("n",$x)])) $w++;
    }
    return
$w;
}

//Usage:
echo get_working_days(strtotime("2011-01-08"));
?>
kovzol at particio dot com 23-Apr-2010 11:19
strtotime(NULL) will give different outputs in PHP 4.4.4 (Debian Linux 4.0) and PHP 5.2.6 (Debian Linux 5.0). The first case gives the number of seconds for today from epoch (1970-01-01), but the second one gives no output.

As a consequence, the following code gives the current year in PHP 4.4.4, but it gives 1970 in PHP 5.2.6:

<?php
 
echo date("Y", strtotime(NULL));
?>

As a workaround,

<?php
 
echo date("Y", strtotime("now"));
?>

will work for both versions well.
ariunbayar 20-Apr-2010 12:03
if you looking for next 31 here it is for PHP5.3
<?php
$d
= 31;
$now = strtotime('2010-06-02');
while (
date('t', $now) < $d){
 
$now = strtotime('last day of next month', $now);
}
echo
date('Y-m-'.$d, $now);
?>
will output "2010-07-31".
nparslow at gmail dot com 08-Apr-2010 12:31
Here is a basic example of a version that works for people outside of the US:

<?php
function strtotime_nonus($date)
{
    if(
is_null($date) or ($date == ""))
        return
False;
   
// break out components with '/', maximum of 3 elements
   
$components = explode("/", $date, 3);
   
$count = count($components);
    if(
$count > 1) // There is a slash
   
{
       
$tmp = $components[0]; // Swap first and second components
       
$components[0] = $components[1];
       
$components[1] = $tmp;
    }
    return
strtotime(implode("/",$components)); // Put back together
}
?>
clarkDONTSPAMMEwise at gmail dot com 29-Mar-2010 05:31
Always use the format strtotime("+1 day") when adding/subtracting units of time rather than manually adding 24*60*60 seconds to a timestamp, for example, as this format works as desired with Daylight Saving Time changes. If your timezone adheres to Daylight Saving Time, a situation like the following may apply to you:

<?php
date_default_timezone_set
('America/Chicago');

// Don't do this:
$today = '2009-11-01';
$tomorrow = strtotime($today) + 24*3600;
print
date('Y-m-d', $tomorrow);
// Output: 2009-11-01

// Do this instead:
$today = '2009-11-01';
$tomorrow = strtotime('+1 day', strtotime($today));
print
date('Y-m-d', $tomorrow);
// Output: 2009-11-02
Alex Austin 16-Mar-2010 04:18
Seems in PHP5 there are new values that can be passed to the function:

<?php
echo time();
echo
'<br>';
echo
strtotime('noon');
echo
'<br>';
echo
strtotime('midnight');
echo
'<br>';
echo
strtotime('10am');
echo
'<br>';
echo
strtotime('2pm');
?>
karim at sweetcode dot co dot uk 24-Feb-2010 12:17
A handy function I wrote to tell you whether a given date (unix timestamp) is a working day in the UK. i.e. not a bank holiday or weekend day. Returns true or false.

<?php 
function isUkWorkingDay( $utDate )
  {
   
/* weekend? */
   
if( date( 'N', $utDate ) > 5 ){
      return
false;
    }
   
   
/* bank holiday? */
   
$year = date( 'Y', $utDate );

   
$utFirstJan = strtotime( '1st jan ' . $year );

   
$firstJanDay = date( 'N'$utFirstJan );

    if (
$firstJanDay > 5 ){ // sat or sun
     
$holidays[] = date( 'Y-m-d', strtotime( 'first monday january ' . $year ));
    }
    else{
     
$holidays[] = date( 'Y-m-d'$utFirstJan) ;
    }

   
$utEasterSunday = easter_date( $year );
   
$holidays[] = date( 'Y-m-d', strtotime( 'last friday', $utEasterSunday ));
   
$holidays[] = date( 'Y-m-d', strtotime( 'next monday', $utEasterSunday ));
   
$holidays[] = date( 'Y-m-d', strtotime( 'first monday may ' . $year ));
   
$holidays[] = date( 'Y-m-d', strtotime( 'last monday june ' . $year )); // end of may B.H.
   
$holidays[] = date( 'Y-m-d', strtotime( 'last monday september ' . $year ));  // end of August B.H.

   
$xmasDay = date( strtotime( '25th december ' . $year ) );
    if (
date( 'N', $xmasDay ) == 5 ){ // falls on friday
     
$holidays[] = date( 'Y-m-d', $xmasDay );
     
$holidays[] = date( 'Y-m-d', strtotime( 'next monday', $xmasDay ));
    }
    if (
date( 'N', $xmasDay ) > 5 ){ // falls on sat or sun
     
$holidays[] = date( 'Y-m-d', strtotime( 'next monday', $xmasDay ));
     
$holidays[] = date( 'Y-m-d', strtotime( 'next tuesday', $xmasDay ));
    }
    if (
date( 'N', $xmasDay ) < 5 ){ // falls on mon to thurs
     
$holidays[] = date( 'Y-m-d', $xmasDay );
     
$holidays[] = date( 'Y-m-d', strtotime( 'next day', $xmasDay ));
    }

    return( !
in_array( date( 'Y-m-d', $utDate ), $holidays ) ) ;
  }
?>
octavio 17-Feb-2010 10:47
This function calculates if date2 is within an interval of seconds from date1.

<?php
function is_on_interval($date1,$date2,$interval){
   
$dat2=strtotime($date2);
   
$dat3=strtotime('+'.$interval.' second '.$date1);
   
    if(
$dat2>=$dat3){
        return
false;
    }
    else
    {
        return
true;
    }
}

$date1='2009-08-18 00:02:00';
$date2='2009-08-18 00:05:00';
?>

$date2 is 180 seconds from $date1.

<?php is_on_interval($date1,$date2,'120'); ?>
will return false.

<?php is_on_interval($date1,$date2,'180'); ?>
will return true.

<?php is_on_interval($date1,$date2,'220'); ?>
will return true.
Adam J. Forster 11-Feb-2010 03:08
You can use strtotime to get the date of the last day of the previous month:

<?php
    date
("Y-m-d", strtotime("2010-03-00")); #Returns 2010-02-28
?>
katylava at gmail dot com 08-Feb-2010 07:04
You should play around with strtotime() before you decide what it can't do.  for example:

<?php

# on 2/8/2010
date('m/d/y', strtotime('first day')); # 02/01/10
date('m/d/y', strtotime('last day')); # 02/28/10
date('m/d/y', strtotime('last day next month')); # 03/31/10
date('m/d/y', strtotime('last day last month')); # 01/31/10
date('m/d/y', strtotime('2009-12 last day')); # 12/31/09 - this doesn't work if you reverse the order of the year and month
date('m/d/y', strtotime('2009-03 last day')); # 03/31/09
date('m/d/y', strtotime('2009-03')); # 03/01/09
date('m/d/y', strtotime('last day of march 2009')); # 03/31/09
date('m/d/y', strtotime('last day of march')); # 03/31/10
?>
emig647 at yahoo.com 18-Dec-2009 08:23
Some have added their fixes for adding 1 month to a time. The problem I find with other fixes is if you are on the 30th (10-30-09) of a month that isn't the last day and add one month to their time, it goes to 1 day less than the last day of the previous month's day. (11-29-09).

Here is my fix for adding 1 month so it's equal to of the previous month day or the last day of the month if it's less than the previous month day.

<?php

$anniversary
= "2008-09-30";
$newChargeDate = strtotime($anniversary);
$newChargeDate = addRealMonth($newChargeDate);

print
date("Y-m-j", $newChargeDate);

//////////////////////////////////////////////////////
// Get the last day of the month
function lastDayOfMonth($month = '', $year = '')
{
   if (empty(
$month)) {
     
$month = date('m');
   }
   if (empty(
$year)) {
     
$year = date('Y');
   }
  
$result = strtotime("{$year}-{$month}-01");
  
$result = strtotime('-1 second', strtotime('+1 month', $result));
   return
date('Y-m-d', $result);
}

function
addRealMonth($timeStamp)
{
   
// Check if it's the end of the year and the month and year need to be changed
   
$tempMonth = date('m', $timeStamp);
   
$tempYear  = date('Y', $timeStamp);
    if(
$tempMonth == "12")
    {
       
$tempMonth = 1;
       
$tempYear++;
    }
    else
       
$tempMonth++;
   
   
$newDate = lastDayOfMonth($tempMonth, $tempYear);
    return
strtotime($newDate);
}

?>

This will output 2008-10-30. Or 2009-02-28 if the $anniversary is 2009-01-30. Hope this helps!
kendsnyder at gmail dot com 06-Nov-2009 05:54
Watch out when using strtotime() on a string that might begin with "0000-00-00" as MySQL stores "null" dates on a not-null date column. The value returned by strtotime("0000-00-00") varies by php version. Consider the following:

<?php
date
('Y-m-d',strtotime('0000-00-00 00:00:00'));
// returns "1969-12-31" on the following versions:
//   Win XP php 5.2.9-2
//   Win 7 php 5.3.0
//   RHEL 5 php 5.2.8
// but returns "-0001-11-30" on RHEL 5 php 5.2.10!

// consider checking for "zero" dates. e.g.:
function formatDate($format,$dateStr) {
  if (
trim($dateStr) == '' || substr($dateStr,0,10) == '0000-00-00') {
    return
'';
  }
 
$ts = strtotime($dateStr);
  if (
$ts === false) {
    return
'';
  }
  return
date($format,$ts);
}
?>
Leon F. 04-Nov-2009 02:58
I needed to generate timestamps for specific days of the week in a month (e.g. the 2nd wednesday or the 3rd friday).  After messing about with different syntax, I found this works pretty consistently:

<?php
strtotime
('+0 week sun nov 2009'); // first sunday in nov 2009
strtotime('+1 week sun nov 2009'); // second sunday
strtotime('-1 week sun nov 2009'); // last sunday in oct 2009
?>

This is helping me considerably in parsing ical spec's RRULE sets for example.
heiko dot dressler at dresden-it dot de 22-Oct-2009 03:27
here is a simple function to compare dates and build ranges. 
<?php
$germanDates
= array('10.10.2009','25.12.2009',
'01.02.2009','11.10.2009',
'12.10.2009','13.10.2009',
'11.10.2010','01.03.2010',
'28.02.2010');

$DateArray = array();
$rangeArray=array();
foreach(
$germanDates as $Index=>$Date)
{
   
// create timestamp from german date [ easy :-) ]
   
$DateArray[$Date]= strtotime($Date);
   
}
// sort timestamps
asort($DateArray);
// read the array and create ranges
$RangeIndex = 0;
$Counter = 0;
$ReadDateStamp = 0;
foreach(
$DateArray as $Index=>$Datum)
{
    if(
$Counter<=0)
    {
       
// init first value and create range array
       
$rangeArray[$RangeIndex][$Index]=$Datum;
       
    }else{
       
// compare new date mit Readstamp
       
$Diff = $Datum - $ReadDateStamp;
        if(
$Diff != 86400)
        {
           
$RangeIndex++;
        }
       
$rangeArray[$RangeIndex][$Index]=$Datum;
    }
   
$ReadDateStamp = $Datum;
   
$Counter++;
}

?>
86400 = 1 day
kooshal at live dot com 21-Oct-2009 01:59
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
flexibill2001 at hotmail dot com 09-Oct-2009 07:38
lot of people said that there is bug in strtotime method like given in this example:

<?php echo date( "Y-m-d", strtotime( "2009-01-31 +1 months" ) )."<br>"; ?>

this gives 03-03-2009 instead of 28-02-2009

here is work arround for this bug.

<?php
/// n=no of months  , $y =year, $m = month, $d = day , $t = + or -

function NewMonthDate($n,$y,$m,$d,$t)
    {
               
        for(
$i=1; $i <= $n; $i++)
            {
            if(
$t=="+")
                {
               
$pmonth=$m+$i;   
                }
            if(
$t=="-")
                {
               
$pmonth=$m-$i;   
                }
       
       
$pyear=$y;
       
$aa=1;
       
       
       
/////////////////this will show lastmonth//////////////
       
$lastmonth = mktime(0, 0, 0, $pmonth, $aa$pyear);
       
        
$smonth=date("m",$lastmonth);
        
$syear=date("Y",$lastmonth);
        
$ndays=date("t",$lastmonth);
       
$valarray=array($smonth,$syear,$ndays);
               
       
$mm=$mm+$ndays;
       
            }
           
       
$basedate="$pyear-$m-$d";
       
$date2 = strtotime("$basedate $t$mm days");   
       
       
$date1=date("d-m-Y",$date2);
        return 
$date1;
           
    }  
////

$n=1;
$y=2009;
$m=01;
$d=31;
$t="+";

$rr=NewMonthDate($n,$y,$m,$d,$t);
print_r($rr);
?>
Anonymous 05-Oct-2009 10:47
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
?>
chris at teamsiems dot com 08-Sep-2009 05:20
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";
}
?>
michal dot kocarek at brainbox dot cz 07-Aug-2009 01:35
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.
Travis Pulley 06-Aug-2009 07:11
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
php at davidstockton dot com 31-Jul-2009 04:04
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.
nan at ladyslipperwebs dot com 12-Jul-2009 11:27
A great little function to see if dates chosen are more than three months apart and if they are, change the end date to three months from the begin date. This is easy to change.

<?php
function daysDifference($endDate, $startDate)
{
   
$startTS = strtotime($startDate);
   
$endTS = strtotime($endDate);
   
$maxTS = strtotime($startDate.' + 3 months');   
    if(
$endTS > $maxTS) {
         
$endTS = $maxTS;
    }
   
$endDate = date('Y-m-d', $endTS); 
    return
$endDate;
}
?>
Killermonk 25-Jun-2009 11:13
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
Merlin at silvercircle dot org 02-Jun-2009 08:52
I've noticed that 'first monday' and '1 monday' are not treated equally.

To get the 1st of june 2009 when searching for the first monday:

Use 'first monday' and start from june 0:

<?php
$time
= strtotime("first monday ", mktime(0, 0, 0, 06, 0, 2009));
echo
"first monday " . date("d-m-Y", $time) . "<br />";
?>

Or use '1 monday' and start from june 1:

<?php
$time
= strtotime("1 monday ", mktime(0, 0, 0, 06, 1, 2009));
echo
"1 monday " . date("d-m-Y", $time) . "<br />";
?>

Took me a long time to figure this out.
viper7 at viper-7 dot com 28-May-2009 10:42
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
PHP_Chimp 14-May-2009 01:08
A warning for those that think that their is only one way to interpret 2009 April 4th...PHP thinks otherwise.
<?php
            $test
= "April 4th 2009";
            if (
strtotime($test) === false) {
                echo
"test == false <br />\n t = $test";
            }
            else {
                echo
"test == true";
            }
?>
Works fine, with the American 'Month Day Year'.
<?php
            $test
= "2009 April 4th";
            if (
strtotime($test) === false) {
                echo
"test == false <br />\n t = $test";
            }
            else {
                echo
"test == true";
            }
?>
Will produce a false result. It seems that even with a 4 figure year that the American date format overrules the obviousness of 2009 April 4th.
dewi at dewimorgan dot com 02-Apr-2009 08:29
Fails for non-US dates where the ordering is uncertain, such as 01/02/2003 - parses this as Feb 1st, rather than Jan 2nd.

If you are parsing dates for a non-US locale, you can flip these elements of your date:

<?php
$y
= $_POST['date'];
if (
preg_match('/^\s*(\d\d?)[^\w](\d\d?)[^\w](\d{1,4}\s*$)/', $y, $match)) {
 
$y = $match[2] . '/' . $match[1] . '/' . $match[3];
}
echo
date('d # m # Y', strtotime($y));
?>

WARNING: Above only works for dates, and breaks for times: 12:30:01 will be converted to 30/12/01.

This absolutely ought to be a flag to strtotime(), either as a boolean "monthfirst" flag, or a boolean "respect my locale" flag. Since it isn't, kludge is needed.
Peter 30-Mar-2009 01:57
If you look for function to convert date from RSS pubDate, always make sure to check correct input format, found that for date("r") or "D, d M o G:i:s T" strtotime may return wrong result.
fuhrysteve at gmail dot com 21-Mar-2009 03:18
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";

?>
CEO at CarPool2Camp dot org 12-Mar-2009 01:41
Another way to get the last day of a given month is to use date('t');
mohrt 27-Feb-2009 05:40
Just an FYI, the Pear Date package addresses many of the topics covered in the notes below (finding last day of month, start date of next week, etc.)
bbutts at stormcode dot net 25-Feb-2009 06:43
After looking around I couldn't find any code that would properly and simply compute the last day of the month.  +1 month will not work ex. 1 month after February 28th is March 3rd.

This line of code returns the last day of the current month:

<?php
echo 'Last day of the month: ' . date('m/d/y h:i a',(strtotime('next month',strtotime(date('m/01/y'))) - 1));
?>

It uses the first of the current month, gets the first of the next month, then subtracts 1 second to give you 11:59pm on the last day of the current month.

Hope this helps someone.
Zoe Blade 11-Feb-2009 04:40
Here's a revised version of [code I originally wrote on 21-JAN-09].  You can work out the number of days left in the month or year like this.  [This version] also works with arbitrary dates given to it rather than only working with the current date:

<?php
function days_left_in_month($isoDate) {
 
$date = explode('-', $isoDate);
 
$date[1]++;
 
$date[1] = str_pad($date[1], 2, '0', STR_PAD_LEFT);

  if (
$date[1] == '13') {
   
$date[0]++;
   
$date[1] = '01';
  }

 
$date[2] = '01';
 
$isoDateNextMonth = implode('-', $date);
  return
ceil((strtotime($isoDateNextMonth) - strtotime($isoDate)) / 86400);
}

echo
days_left_in_month('2009-01-31'); // Much better
?>


[EDIT BY danbrown AT php DOT net: Contains bugfixes by (akniep AT rayo DOT info) on 03-FEB-09 and the original author.]
akniep at rayo dot info 03-Feb-2009 04:37
The "+1 month" issue solved as in MySQL.
========================================
As noted in several comments, PHP's 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:  2009-03-03
<?php
echo date( "Y-m-d", strtotime( "2009-01-31 +1 month" ) );
?>

// MySQL:  2009-02-28
<?php
SELECT DATE_ADD
( '2009-01-31', INTERVAL 1 MONTH );
?>

========================================
If not for consistency with MySQL there are several reasons why one may need a PHP-function that calculates "+1 month" as MySQL does. Certainly, for various kinds of business logic it seems much more intuitiv to land on a date within the subsequent month rather than on a date within the next but one if you calculate "next month" ("+1 month").

The following function calculates a date X months in the future of a given date ($base_time).

<?php

/**
 * Calculates a date lying a given number of months in the future of a given date.
 * The results resemble the logic used in MySQL where '2009-01-31 +1 month' is '2009-02-28' rather than '2009-03-03' (like in PHP's strtotime).
 *
 * @author akniep
 * @since 2009-02-03
 * @param $base_time long, The timestamp used to calculate the returned value .
 * @param $months int, The number of months to jump to the future of the given $base_time.
 * @return long, The timestamp of the day $months months in the future of $base_time
 */
function get_x_months_to_the_future( $base_time = null, $months = 1 )
{
    if (
is_null($base_time))
       
$base_time = time();
   
   
$x_months_to_the_future    = strtotime( "+" . $months . " months", $base_time );
   
   
$month_before              = (int) date( "m", $base_time ) + 12 * (int) date( "Y", $base_time );
   
$month_after               = (int) date( "m", $x_months_to_the_future ) + 12 * (int) date( "Y", $x_months_to_the_future );
   
    if (
$month_after > $months + $month_before)
       
$x_months_to_the_future = strtotime( date("Ym01His", $x_months_to_the_future) . " -1 day" );
   
    return
$x_months_to_the_future;
}
//get_x_months_to_the_future()
   
   
// Tests
// =======

// returns 2009-02-28
echo date( "Y-m-d H:i:s", get_x_months_to_the_future( strtotime( '2009-01-31' ) ) ), "\n";
// returns 2008-02-29
echo date( "Y-m-d H:i:s", get_x_months_to_the_future( strtotime( '2008-01-31' ) ) ), "\n";
// returns 2009-09-30 12:00:00
echo date( "Y-m-d H:i:s", get_x_months_to_the_future( strtotime( '2009-05-31 12:00:00' ), 4 ) ), "\n";

?>
joris dot landman at gmail dot com 29-Dec-2008 08:13
Possible UTC (GMT) version of strtotime()

<?php

function gmstrtotime($my_time_string) {
    return(
strtotime($my_time_string . " UTC"));
}

?>

strtotime() assumes that anything you feed into it, uses the server's "relative" time zone.
By adding " UTC" to any input string, you make it "absolute".
will at mooloop dot com 15-Oct-2008 04:25
A simple way to work out someone's age in years:

<?php
$dob
= '1984-09-04';
$age = date('Y') - date('Y', strtotime($dob));
if (
date('md') < date('md', strtotime($dob))) {
   
$age--;
}
?>
emperorshishire at gmail dot com 10-Oct-2008 04:26
Just a quick note on dealing with non-standard strings:
If you attempt to parse single, random letters, strtotime() will give you apparently random output.  Because strtotime() uses C's get_date() function, all dangling single letters are interpreted as military time zones.  So, for example:

<?php
echo date('r', time())."<br />\n";
echo
date('r', strtotime('L'))."<br />\n";
echo
date('r', strtotime('1999L'));
?>

will return:

Fri, 10 Oct 2008 12:12:28 -0400
Thu, 09 Oct 2008 21:12:28 -0400
Sat, 09 Oct 1999 21:12:28 -0400

when executed in the UTC -5 timezone, because "L" is defined as UTC+11.  J will return unix epoch, because it is not defined as a military time zone, while \t and \n both return the current time, as does a space.  All other single characters return unix epoch, because they are not defined.  The returned time is relative to the specified time, so the third example returns the current day and time in the year 1999, in timezone UTC +11.
orel16 at ya dot ru 25-Sep-2008 05: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
orel16 at ya dot ru 12-Sep-2008 06: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 />";
?>
raph 09-Sep-2008 09: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";
}
?>
pistachio 03-Sep-2008 03: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.
Carl 02-Sep-2008 10:51
strtotime returns time() for any string that begins with "eat" (case insensitive):

<?php
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"
php at info-svc dot com 22-Aug-2008 04: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:

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

<?php
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
jaymin at gmx dot net 08-Aug-2008 01:48
strtotime() seems to treat dates delimited by slashes as m/d/y and dates delimited by dashes are treated as d-m-y.

<?php
print date('Y-m-d', strtotime("06/08/2008"));
?>

returns 2008-06-08

while

<?php
print date('Y-m-d', strtotime("06-08-2008"));
?>

returns 2008-08-06

Using PHP 5.2.6
rohanshenoy at w3hobbyist dot com 23-Jul-2008 12: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.
enkrs 01-Jul-2008 07: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.
?>
Anonymous 24-Jun-2008 07:59
When using a custom timestamp and adding a day to it, this works:

<?php strtotime("20080601 +1 day"); ?>

this does not:

<?php 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. :)
timstamp.co.uk 10-Jun-2008 03: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.
richard at happymango dot me dot uk 10-Jun-2008 10:41
If you want to round a timestamp to the closest specified increment, for example to the closest 15 minutes, then this function could help

Definition:
int roundTime ( string $increment[, int $timestamp] )

Parameters:
$increment is a string like you would for strtotime (but dont add a + or - to the front)
$timestamp (optional) the timestamp used to calculate the returned value.

Return Value:
returns timestamp

this function only works for increments less than or equal to an hour

Its not pretty but it works.

<?php

function roundTime($increment, $timestamp=0)
{
    if(!
$timestamp) $timestamp = time();
   
   
$increment = strtotime($increment, 1) - 1;
   
$this_hour = strtotime(date("Y-m-d H:", strtotime("-1 Hour", $timestamp))."00:00");
   
$next_hour = strtotime(date("Y-m-d H:", strtotime("+1 Hour", $timestamp))."00:00");

   
$increments = array();
   
$differences = array();
   
    for(
$i = $this_hour; $i <= $next_hour; $i += $increment)
    {
       
$increments []= $i;
       
$differences []= ($timestamp > $i)? $timestamp - $i : $i - $timestamp;
    }
   
   
arsort($differences);
   
   
$key = array_pop(array_keys($differences));
   
    return
$increments[$key];
}

////////////
//EXAMPLE //
////////////

$result = roundtime("15 minutes");

echo
date("H:i", time())." rounded to closest $increment is ".date("H:i", $result);

//11:24 rounded to closest 15 minutes is 11:30
?>

Here are two other functions. ceilTime() and floorTime() which round up or down to the specified increment respectively.
 
<?php
//RSS: 10/06/08 rounds a timestamp to the next specified increment
//only works for increments less than or equal to 1 hour
//EG: ceilTime("15 Minutes"); rounds the time right now to the next 15 minutes 11:12 rounds to 11:15
function ceilTime($increment, $timestamp=0)
{
    if(!
$timestamp) $timestamp = time();
   
   
$increment = strtotime($increment, 1) - 1;
   
$this_hour = strtotime(date("Y-m-d H:", strtotime("-1 Hour", $timestamp))."00:00");
   
$next_hour = strtotime(date("Y-m-d H:", strtotime("+1 Hour", $timestamp))."00:00");

   
$increments = array();
   
$differences = array();
   
    for(
$i = $this_hour; $i <= $next_hour; $i += $increment)
    {
        if(
$i > $timestamp) return $i;
    }
}

//RSS: 10/06/08 rounds a timestamp to the last specified increment
//only works for increments less than or equal to 1 hour
//EG: floorTime("15 Minutes"); rounds the time right now to the last 15 minutes 11:12 rounds to 11:00
function floorTime($increment, $timestamp=0)
{
    if(!
$timestamp) $timestamp = time();
   
   
$increment = strtotime($increment, 1) - 1;
   
$this_hour = strtotime(date("Y-m-d H:", strtotime("-1 Hour", $timestamp))."00:00");
   
$next_hour = strtotime(date("Y-m-d H:", strtotime("+1 Hour", $timestamp))."00:00");

   
$increments = array();
   
$differences = array();
   
    for(
$i = $next_hour; $i >= $this_hour; $i -= $increment)
    {
        if(
$i < $timestamp) return $i;
    }
}

?>
rtwolf at spymac dot com 01-Jun-2008 02: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).
php dot net at dubaifaqs dot com 09-May-2008 07: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.
frank at crop-circle dot net 31-Jan-2008 09: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
?>
chris at cmbuckley dot co dot uk 21-Jan-2008 01: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
?>
xini [at] gmx [dot] de 10-Dec-2007 04: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
?>
andrew dot myers at civicwifi dot com 05-Dec-2007 06: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

?>
thalesjacobi at thalesjacobi dot net 06-Nov-2007 09: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 :

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

<?php
$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.
Beat 01-Oct-2007 08: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

?>

Here the workaround 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

?>
btherl at yahoo dot com dot au 03-Sep-2007 02:33
Another inconsistency between versions:

<?php
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.
ThomasK 19-Jul-2007 01: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 05: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...
Ian Fieggen 01-Jul-2007 02: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 01-Jun-2007 03: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 13-May-2007 03: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 08-Apr-2007 01: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
02-Mar-2007 11: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 08: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).
LigH 16-Jan-2007 10: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:

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

Wrong:

<?php
$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");
?>
Bandit 07-Nov-2006 01:06
So I wanted a little function to output an easy to read but inaccurate date. I came up with the following (probably very inefficient) little function;

<?php
   
function ezDate($d) {
       
$ts = time() - strtotime(str_replace("-","/",$d));
       
        if(
$ts>31536000) $val = round($ts/31536000,0).' year';
        else if(
$ts>2419200) $val = round($ts/2419200,0).' month';
        else if(
$ts>604800) $val = round($ts/604800,0).' week';
        else if(
$ts>86400) $val = round($ts/86400,0).' day';
        else if(
$ts>3600) $val = round($ts/3600,0).' hour';
        else if(
$ts>60) $val = round($ts/60,0).' minute';
        else
$val = $ts.' second';
       
        if(
$val>1) $val .= 's';
        return
$val;
    }
?>

Then I use it as follows;

<?php
   
echo ucwords(ezDate('2006-09-07 18:42:00')).' Ago';
?>

Which would output;

    2 Months Ago

I add an acronym tag around the output also, so my users can mouse-over for the exact date.

Hope it helps someone!
sgutauckis 05-Oct-2006 07: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.
shaver at qspeed dot com 11-Jan-2006 04: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
Philippe Jausions -at- 11abacus.com 28-Sep-2005 03: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"]
sholland at napervillegi dot com 29-Aug-2005 01: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
tero dot totto at kymp dot net 15-Aug-2005 06: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".
dcahhNOSPAM at gmx dot de 15-Jul-2005 09: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
timvw at users dot sourceforge dot net 12-Jul-2005 11: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
?>
ruben at wipkip dot com 28-Jun-2005 12: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.
LittleZephyr at nillahood dot net 09-May-2005 08: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/Date-input-formats.html#SEC114
Ed Lecky-Thompson 26-Apr-2005 04:02
Here's a quick function which can [compliment] strtotime, and will work fine on dates pre-1970 (i.e. it will return a negative number as expected).

This negative time stamp seems to be supported as an input parameter by methods like date() up to a point, but if you get crazy and start talking about dates in the 1700s (everybody was using PHP3 back then, of course) it gets upset.

For those of you doing staff databases and so forth, of course, this is probably fine - it's definitely OK for any dates post 1900, and this value has been hard coded into the function below.

<?php
   
function safestrtotime($strInput) {
       
$iVal = -1;
        for (
$i=1900; $i<=1969; $i++) {
           
# Check for this year string in date
           
$strYear = (string)$i;
            if (!(
strpos($strInput, $strYear)===false)) {
               
$replYear = $strYear;
               
$yearSkew = 1970 - $i;
               
$strInput = str_replace($strYear, "1970", $strInput);
            };
        };
       
$iVal = strtotime($strInput);
        if (
$yearSkew > 0) {
           
$numSecs = (60 * 60 * 24 * 365 * $yearSkew);
           
$iVal = $iVal - $numSecs;
           
$numLeapYears = 0;        # Work out number of leap years in period
           
for ($j=$replYear; $j<=1969; $j++) {
               
$thisYear = $j;
               
$isLeapYear = false;
               
# Is div by 4?
               
if (($thisYear % 4) == 0) {
                   
$isLeapYear = true;
                };
               
# Is div by 100?
               
if (($thisYear % 100) == 0) {
                   
$isLeapYear = false;
                };
               
# Is div by 1000?
               
if (($thisYear % 1000) == 0) {
                   
$isLeapYear = true;
                };
                if (
$isLeapYear == true) {
                   
$numLeapYears++;
                };
            };
           
$iVal = $iVal - (60 * 60 * 24 * $numLeapYears);
        };
        return(
$iVal);
    };
?>
miamiseb at nospam_gmail dot com 22-Apr-2005 04: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.
05-Apr-2005 06:45
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.
gabrielu at hotmail dot com 05-Apr-2005 04: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:

    <?php 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).

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

    <?php date('m/d/Y', strtotime('-1 week' ,strtotime('Wednesday', '2005-04-05'))); ?>
bishop 09-Dec-2004 04: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.
cryogen at mac dot com 06-Apr-2004 06:39
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!
?>
kyle at frozenonline dot com 01-Jan-2004 11: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.

 
show source | credits | sitemap | contact | advertising | mirror sites