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

search for in the

time> <strptime
Last updated: Fri, 27 Jun 2008

view this page in

strtotime

(PHP 4, PHP 5)

strtotime — Parse 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 a US 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 GMT), 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.

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.

Parameters

time

The string to parse, according to the GNU » Date Input Formats syntax. Before PHP 5.0.0, microseconds weren't allowed in the time, since PHP 5.0.0 they are allowed but ignored.

now

The timestamp used to calculate the returned value.

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 message if using the system settings or the TZ environment variable. See also date_default_timezone_set()

ChangeLog

Version Description
5.1.0 It now returns FALSE on failure, instead of -1.
5.1.0

Now issues the E_STRICT and E_NOTICE time zone errors.

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

Warning

In PHP 5 up to 5.0.2, "now" and other relative times are wrongly computed from today's midnight. It differs from other versions where it is correctly computed from current time.

Warning

In PHP versions prior to 4.4.0, "next" is incorrectly computed as +2. A typical solution to this is to use "+1".

Note: The valid range of a timestamp is typically from Fri, 13 Dec 1901 20:45:54 GMT to Tue, 19 Jan 2038 03:14:07 GMT. (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.

See Also



time> <strptime
Last updated: Fri, 27 Jun 2008
 
add a note add a note User Contributed Notes
strtotime
enkrs
01-Jul-2008 03: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.
?>
promotions at jdnash dot org
26-Jun-2008 06:50
Alex, it will return false for a null date.

// reading from my login tracking table (MySQL)
$db_content = myconnect(PRIVATE_LOGIN,PRIVATE_PASSWORD);

$sql = "SELECT * FROM `keys`";
$sql .= " WHERE `login`='".$_SESSION['login']."'";
$sql .= " AND `password`='".$_SESSION['password']."';";

$result = mysql_query($sql, $db_content) or die(mysql_error());

if ($result){
    $row=mysql_fetch_array($result);
    $date_expire = $row['date_expire'];

    if( !strtotime($date_expire) ){ // false if bad date
        ... fix the problem here ...
    }
...
}

Please note that this DOES NOT cover the cases where strtotime() has guessed at what was intended in $date_expire. To protect yourself you can also check that the date as converted actually matches the date strtotime() thinks that you want:

$x = date("Y-m-d",strtotime($date_expire));
if($x !== $date_expire){ // bad conversion
    ... do something to fix the problem here ...
}

>>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.
highermind.org
25-Jun-2008 10:41
Concerning the "+1 month == 30.5 days" issue:

The developer hubris surrounding this in the bug database is annoying: irregardless of how GNU date works there appears to be a genuine business need that adding one month to Jan 31 gives Feb 28 and not March 2.

Think of an invoicing system for a service provider: if a customer's billing date is usually the 31st, having February's bill due on March 2nd will look out of place on a report, and your customers/employer/etc. will blame you, not GNU date.

Also, the php 5.3 "last day of next month" $time string does not appear relevant. What is really needed is a separate string that can take a dynamic number of months and give us the date for the next month as humans would understand it: "+{$months} realmonth" or "+{$months} manmonth" or some such.

In lieu of that, here are two functions to add and subtract months no matter the end of month date.

if (!funtion_exists('date_addmonths'))
    {
    function date_addmonths($n_months, $timestamp=null)
        {
        if (is_null($timestamp))    $timestamp=time();
        $timestamp_midmonth    = mktime(12, 0, 0, date('n', $timestamp)+$n_months, 15, date('Y', $timestamp));
        return date('t', $timestamp) > date('t', $timestamp_midmonth) ? strtotime(date('t F Y', $timestamp_midmonth)) : strtotime(date(date('d', $timestamp).' F Y', $timestamp_midmonth));
        }
    }

if (!funtion_exists('date_submonths'))
    {
    function date_submonths($n_months, $timestamp=null)
        {
        if (is_null($timestamp))    $timestamp=time();
        $timestamp_midmonth    = mktime(12, 0, 0, date('n', $timestamp)-$n_months, 15, date('Y', $timestamp));
        return date('t', $timestamp) > date('t', $timestamp_midmonth) ? strtotime(date('t F Y', $timestamp_midmonth)) : strtotime(date(date('d', $timestamp).' F Y', $timestamp_midmonth));
        }
    }
Anonymous
24-Jun-2008 03: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. :)
Dieter D
20-Jun-2008 09:43
Doing this:

strtotime('2 months',0);

returns the same as:

strtotime('62 days',0);

So it appears "months" always uses 31 days a month.

BTW i'm on PHP v. 5.2.4.
Alex
19-Jun-2008 01: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.
timstamp.co.uk
10-Jun-2008 11: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 07:12
In complement to the my last post, roundTime(), 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;
    }
}

?>
richard at happymango dot me dot uk
10-Jun-2008 06:43
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
?>
rtwolf at spymac dot com
31-May-2008 10: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 03: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.
Jo H
07-May-2008 05:44
British/European summer time starts on the last Sunday in March and ends on the last Sunday in October, at 01:00 GMT.

While I could use date("I") to determine whether a date is in summer time or not, my server is on American time and American daylight savings uses different rules.

I needed to determine whether a given date falls within the British Summer Time season, and if so convert it back to GMT. This works for me:

<?php

function BST_finder ($dt) {
   
$BSTstart=strtotime("last Sunday",gmmktime(0,0,0,4,1))+3600; // plus 3600 seconds to make it 1 a.m.
   
$BSTend=strtotime("last Sunday",gmmktime(0,0,0,11,1))+3600;
    if (
$dt>=$BSTstart and $dt<=$BSTend) {
       
$dt=$dt-3600;
    }
    return
$dt;
}

$date="2008-10-04 02:45:00";
$dt=strtotime($date);
$corrected_date=BST_finder($dt);
$pretty_date=date("Y-m-d H:i:s",$corrected_date); // 2008-10-04 01:45:00

?>

(built upon Ian Fieggen's comment below)
Anonymous
01-May-2008 04:55
Previous commenter worte:

"
Get the first day of the month:

<?php
$time
= time();
      
echo
date('m/d/Y', strtotime('1 '.date('F', $time).' '.date('Y', $time)));
?>
"

Or just:

date('m/01/Y')

every month begins with a 1st ;)
till at pralinenschachtel dot de
01-May-2008 04:40
In some versions strtotime() can't handle time offsets like: +1000, UTC, WET, UTC+0, ...

<?php
print strtotime('Thu Apr 03 18:26:36 +0000 2008'); // PHP 4.4.4: -1
print strtotime('Thu Apr 03 18:26:36 +0000 2008'); // PHP 5.2.5: 1207247196
?>

I made the following function to get always the correct timestamp. Just adjust the str_replace() to your timestamp pattern.

<?php

function str2time($string) {

   
$time = strtotime($string);

    if (!
$time) {

       
$offset = date('Z');
       
$string = str_replace('+0000', '', $string);

        if (
$offset > 0) {
            print
strtotime($string) + $offset;
        } else {
            print
strtotime($string) - $offset;
        }

    }

    return
$time;

}
?>
Adam Docherty aka Lobos
30-Apr-2008 10:50
Get the first day of the month:

<?php
$time
= time();
       
echo
date('m/d/Y', strtotime('1 '.date('F', $time).' '.date('Y', $time)));
?>
Anonymous
22-Apr-2008 11:19
public function between_dates("Y-m-d", "Y-m-d"){
  $array = explode("-", $start);
  $i       = 1;   
  while($start != $to){
    $date[] = $start = date("Y-m-d", mktime(1,1,1,$array[1],$array[2] + $i,$array[0]));
    $i++;
        }
  return $date;   
}
brian at diamondsea dot com
14-Apr-2008 10:53
I am having problems with the timhavens's <i>dates_betweeen_dates()</i> script not returning proper output for calls like:

<?
print_r
(dates_between_dates('2008-04-14', '2008-04-14'));
print_r(dates_between_dates('2008-04-14', '2008-04-15'));
?>

Here is a function that returns the expected results:

<?
/*
 *  dates_between_dates - Returns array of all dates between $date1 and $date2
 *
 *  @param start_date Start-Date of range
 *  @param end_date End-Date of range
 *  @returns array dates
 */
function dates_between_dates($start_date, $end_date) {
   
// Standardize date formats
   
$start_date = date('Y-m-d', strtotime($start_date));
   
$end_date = date('Y-m-d', strtotime($end_date));

   
// if $end_date is later, swap the dates
   
if (strtotime($start_date) > strtotime($end_date)) {
       
$a = $start_date;
       
$start_date = $end_date;
       
$end_date = $a;
    }

   
// initialize array with start date
   
$return_array = array($start_date);

   
// Initialize loop counter date
   
$the_date = $start_date;

   
// loop through days
   
while ($the_date != $end_date) {
       
$the_date = date('Y-m-d', strtotime($the_date."+1 day"));
       
$return_array[] = $the_date;
    }

    return
$return_array;
}
?>
tonycarbone at trackking dot org
27-Mar-2008 04: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"
Raymond Irving
25-Mar-2008 11:50
Here’s a link to a Date Class library that can be used as a minor replacement for the strtotime() function. It supports timestamps for dates greater than 2038 and lesser than 1970 in both PHP4 and PHP5

Check it out here:

http://xwisdomhtml.com/dateclass.html
timhavens at gmail dot com
12-Mar-2008 09:43
I needed a function to return all the dates between two dates.  I've looked for something like this in the past an didn't find it.  I'm sure there are better ways, but I wanted to post this in case it was helpful to others.

function dates_between_dates($date1,$date2) {
    $return_array = array();
    $num_days = date_diff('d',$date1,$date2)+1;

    for($i=0;$i<=$num_days;$i++) {
       $return_array[] = date('Y-m-d',strtotime($date1."+$i day"));
    }

    return $return_array;
}

function date_diff($interval, $date1, $date2)
{

   //convert the dates into timestamps
  $date1 = strtotime($date1);
  $date2 = strtotime($date2);
  $seconds = $date2 - $date1;

   if ($seconds < 0)
   {
           $tmp = $date1;
           $date1 = $date2;
           $date2 = $tmp;
           $seconds = 0-$seconds;
   }

   //reconvert the timestamps into dates
   if ($interval =='y' || $interval=='m') {
       $date1 = date("Y-m-d h:i:s", $date1);
       $date2=  date("Y-m-d h:i:s", $date2);
   }

   switch($interval) {
       case "y":
           list($year1, $month1, $day1) = split('-', $date1);
           list($year2, $month2, $day2) = split('-', $date2);
           $time1 = (date('H',$date1)*3600) + (date('i',$date1)*60) + (date('s',$date1)
);
           $time2 = (date('H',$date2)*3600) + (date('i',$date2)*60) + (date('s',$date2)
);
           $diff = $year2 - $year1;

           if($month1 > $month2) {
               $diff -= 1;
           } elseif($month1 == $month2) {
               if($day1 > $day2) {
                   $diff -= 1;
               } elseif($day1 == $day2) {
                   if($time1 > $time2) {
                       $diff -= 1;
                   }
               }
           }
           break;
       case "m":
           list($year1, $month1, $day1) = split('-', $date1);
           list($year2, $month2, $day2) = split('-',$date2);
           $time1 = (date('H',$date1)*3600) + (date('i',$date1)*60) + (date('s',$date1)
);
           $time2 = (date('H',$date2)*3600) + (date('i',$date2)*60) + (date('s',$date2)
);
           $diff = ($year2 * 12 + $month2) - ($year1 * 12 + $month1);
           if($day1 > $day2) {
               $diff -= 1;
           } elseif($day1 == $day2) {
               if($time1 > $time2) {
                   $diff -= 1;
               }
           }
           break;
       case "w":
           // Only simple seconds calculation needed from here on
           $diff = floor($seconds / 604800);
           break;
       case "d":
           $diff = floor($seconds / 86400);
           break;
       case "h":
           $diff = floor($seconds / 3600);
           break;
       case "i":
           $diff = floor($seconds / 60);
           break;
       case "s":
           $diff = $seconds;
           break;
   }

   return $diff;
}
jimworm at gmail dot com
11-Mar-2008 06:25
To get the first day of any month, simply force the day using the formatting option of date(), like this:

<?php

// Find the first day of last month, formatted d/m/Y
$lastmonth01 = date("01/m/Y", strtotime("last month"));

?>
Jacob (Jack) Gryn
04-Mar-2008 05:10
Sorry, just a minor correction to my code below, apparently, it the endDate does not include itself, so the line that reads:

       $endtime = strtotime($endDate);

should instead read

       $endtime = strtotime("+1 day ", strtotime($endDate));

Also, I'm using an old version of php (4.1.2), so the 'next $day' may function differently according to the comment above.
Anonymous
04-Mar-2008 07:43
Requirement:
From a date of birth, work out an age on a given date.

Problem:
Solutions I found were not accurate enough, not incorporating leap years.. and often up to a week out for a 30 year old.

Solution:
While the following still probably has it's flaws, it worked for me to enough precision.

<?php

//Get the date of birth as timestamp from american format
$birthtime = strtotime( $birth_month. "/" . $birth_day . "/" . $birth_year );

//Get the required date as timestamp (or could do time() for today)
$reqtime = strtotime( $req_month. "/" . $req_day . "/" . $req_year );

//Simple Calculation to get age
$calc_age = floor ( ($reqtime - $birthtime) / 60*60*24*365.25) ) ;

?>

Testing:
I've tested this for those aged 18 to 90. And it is accurate to the day. Obviously it doesn't take time of birth into account.. but really.. who cares?
Jacob (Jack) Gryn
03-Mar-2008 01:35
Just an correction to Jeff Stevenson's function of 2008-02-02.

That code as is didn't really work, but the right idea was there.. (e.g., the $days parameter wasn't really used, and the sort didn't save) There were a few typos and minor other things, try the code below instead... 

function getDaysBetween($startDate, $endDate, $days)
{
    $days = explode(',', $days);
    $dates = array();
    foreach($days as $day)
    {
        $newDate = $startDate;
        switch ($day){
            case 'Su':
            case 'Sun':
                $day = 'Sun';
                break;
            case 'M':
            case 'Mon':
                $day = 'Mon';
                break;
            case 'T':
            case 'Tu':
            case 'Tue':
                $day = 'Tue';
                break;
            case 'W':
            case 'Wed':
                $day = 'Wed';
                break;
            case 'Th':
            case 'Thu':
            case 'Thur':
                $day = 'Thu';
                break;
            case 'F';
            case 'Fri';
                $day = 'Fri';
                break;
            case 'S':
            case 'Sat':
                $day = 'Sat';
                break;
            default:
                continue 2;
        }
        $curtime = strtotime("next $day", strtotime($startDate));
        $endtime = strtotime($endDate);
        while($curtime <= $endtime)
        {
           $dates[] = date('Y-m-d', $curtime);
           $curtime=strtotime("next 2 $day", $curtime);
        }
    }

    $dates=array_unique($dates);
    sort($dates);
    return $dates;
}
php at bucksvsbytes dot com
23-Feb-2008 09: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).
ecziegler at gmail
21-Feb-2008 07:01
Took me 20 minutes to find a way to get the first day of the month with this function... I believe there is a smarter way but all I could make was

date('d/m/Y', strtotime("first day", strtotime(date('F 0 Y'))));
user at example dot com
15-Feb-2008 11:35
How to work around the problem of not accepting time with @ sign before it:
<?php
 
function strtotime2($t) {
  if(
$t[0]=='@') return 0+substr($t,1);
  else return
strtotime($t);
 }
?>
Jeff Stevenson
02-Feb-2008 08:14
This may not be the best way to do it, but it works very well for me.

<?php
/**
 * Function used to find the dates of specific days between
 * two different dates.  So, if you want to find all the
 * mondays and all the wednesdays between 2 dates, this
 * function is right for you.
 *
 * @param string $startDate e.g. 2007-01-31
 * @param string $endDate e.g. 2007-12-31
 * @param csv string $days e.g. 'Su,M,T,W,TH,F,S';
 * @return array
 */
function getDaysBetween($startDate, $endDate, $days){
   
$endDate = strtotime($endDate);
   
$days = explode(',', 'M,W');
   
$dates = array();
    foreach(
$days as $day){
       
$newDate = $startDate;
        switch (
$day){
            case
'Su':
               
$day = 'Sun';
                break;
            case
'M':
               
$day = 'Mon';
                break;
            case
'T':
               
$day = 'Tue';
                break;
            case
'W':
               
$day = 'Wed';
                break;
            case
'Th':
               
$day = 'Thur';
                break;
            case
'F';
           
$day = 'Fri';
            break;
            case
'S':
               
$day = 'Sat';
                break;
        }
        while((
$date = strtotime($newDate)) <= $endDate){
           
$dates[] = date('Y-m-d', $date)."\n";
           
$newDate = date('Y-m-d', $date).' next '.$day;
        }
    }

   
sort(array_unique($dates));
    return
$dates;
}
?>

Example:

$startDate = '2006-08-28';
$endDate = '2006-10-09';
$days = 'M,W';

then

getDaysBetween($startDate, $endDate, $days);

returns

Array
(
    [0] => 2006-08-28
    [1] => 2006-09-04
    [2] => 2006-09-11
    [3] => 2006-09-18
    [4] => 2006-09-25
    [5] => 2006-10-02
    [6] => 2006-10-09
    [7] => 2006-08-28
    [8] => 2006-08-30
    [9] => 2006-09-06
    [10] => 2006-09-13
    [11] => 2006-09-20
    [12] => 2006-09-27
    [13] => 2006-10-04
)
frank at crop-circle dot net
31-Jan-2008 04: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
?>
enyone
31-Jan-2008 05:01
More intelligent function to switch between months:

    private function MoveMonth( $absolution, $timestamp )
    {
      $day = intval( date( "d", $timestamp ) );
      $month = intval( date( "m", $timestamp ) );
      $year = intval( date( "Y", $timestamp ) );
      $hour = date( "H", $timestamp );
      $minute = date( "i", $timestamp );
      $second = date( "s", $timestamp );

      // Positive movement
      if( $absolution > 0 )
      {
        $absolution = abs( $absolution );
        for( $abs=0;$abs<$absolution;$abs++ )
        {
          $month ++;
          if( $month > 12 )
          {
            $month = 1;
            $year ++;
          }
        }
      }

      // Negative movement
      else if( $absolution < 0 )
      {
        $absolution = abs( $absolution );
        for( $abs=0;$abs<$absolution;$abs++ )
        {
          $month --;
          if( $month < 1 )
          {
            $month = 12;
            $year --;
          }
        }
      }

      // Prevent from going over a month ( 31.01. --> 31.02. is impossible but 29.02. is ok )
      $daysInMonth = date( 't', mktime( 0, 0, 0, $month, 1, $year ) );
      if( $daysInMonth < $day )
        $day = $daysInMonth;

      return mktime( $hour, $minute, $second, $month, $day, $year );
    }
ian _ channing at hotmail
29-Jan-2008 08:35
This code is for relative dates similar to the add date functionality that C# has.  It allows for negative values to substract dates.

/*pre: format is either 'd' for days,'m' for months or 'y' for years
       length is the number of days/months/years
       date_array is optional,format is getdate()
post:     returns the integer value of the date with the added length
*/
function date_add($length,$format,$date_array=null){
 $new_timestamp = -1;
 $date = is_null($date_array)?getdate():$date_array;

 switch(strtolower($format)){
  case 'd':
   $new_timestamp = mktime(0,0,0,$date["mon"],$date["mday"]+$length,$date["year"]);
   break;
  case 'm':
   $new_timestamp = mktime(0,0,0,$date["mon"]+$length,$date["mday"],$date["year"]);
   break;
  case 'y':
   $new_timestamp = mktime(0,0,0,$date["mon"],$date["mday"],$date["year"]+$length);
   break;
  default:
   break;
 }

 return $new_timestamp;
}
chris at cmbuckley dot co dot uk
21-Jan-2008 08: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 11: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 01: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

?>
php at bucksvsbytes dot com
04-Dec-2007 08: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.
Hayley Watson
25-Nov-2007 04: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.
Hayley Watson
23-Nov-2007 12: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.
jay at jaymunda dot com
15-Nov-2007 07: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
grey580 at yahoo dot com
15-Nov-2007 04: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
thalesjacobi at thalesjacobi dot net
06-Nov-2007 04: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.
Beat
01-Oct-2007 06:41
Here the workaround to the bug of strtotime() found in my previous comment on finding the exact date and time of "3 months ago of last second of this year", using mktime() properties on dates instead of strtotime(), and which seems to give correct results:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

While it's a relatively minor performance difference in a small script, it would be compounded significantly in larger applications or loops.
smartalco
26-Jul-2007 12: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
ThomasK
19-Jul-2007 09: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 01:47
when using strtotime("wednesday"), you will get different results whether you ask before or after wednesday, since strtotime always looks ahead to the *next* weekday.

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

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

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

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

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

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

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

}

example use:

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

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

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

If the current month is December, this capitalises on the fact that the mktime() function correctly accepts a month value of 13 as meaning January of the next year.
matt
31-May-2007 11: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 t