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, 25 Jul 2008

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 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, 25 Jul 2008
 
add a note add a note User Contributed Notes
strtotime
rohanshenoy at w3hobbyist dot com
23-Jul-2008 02:56
This function can be used to convert the timestamp generated by MySQL NOW() function into UNIX timestamp. Example:

Lets say MySQL NOW() returns '2008-07-23 06:07:42'.

<?php
$mysql_now
='2008-07-23 06:07:42';
$time=strtotime($mysql_now);
echo
date(d M y, H:i:s,$time);
//outputs: 23 Jul 08, 06:07:42
?>

Please note that the timestamp returned by mysql NOW() function may be the in the timezone of the server on which it was generated, and not always in GMT.
debbie dot smith at itontap dot com
22-Jul-2008 05:10
the post with the date_addmonths function doesn't really work, and its returning a timestamp not a date.  i find the following function works well for me, to address the same problem.

<?php
# this function is needed for 31-jan-08 + 1 month to give 28-feb-08, etc.
if (!function_exists('time_addmonths'))
{
    function
time_addmonths($n_months, $timestamp=null)
    {
        if (
is_null($timestamp))    $timestamp=time();
       
$newt = strtotime("+$n_months months",$timestamp);
       
$newd = date('d',$newt);
        if (
date('d',$timestamp) != $newd) {
           
# its rolled over to the next month so subtract the extra days
           
$newt = strtotime("-$newd days",$newt);
        }
        return
$newt;
    }
}
?>
dmitry dot kruglov at gmail dot com
18-Jul-2008 06:15
Pretty solution for Australian date format compatibility.
In Australia the date format is: DD/MM/YYYY.
So, 01/05/2008 should be considered as the 1st of May 2008 instead of the 5th of January 2008.

<?php
function strtoautime($datetime)
{
    return
strtotime(preg_replace("/(\d{2})\/(\d{2})\/(\d{2,4})/", "$2/$1/$3", $datetime));
}
?>
soapergem at gmail dot com
15-Jul-2008 04:28
Please note that currently (as of PHP 5.2.6) this function is still slightly broken...

If you request the day of the week that a month begins on in any multiple (for instance, this month started on a Tuesday, so if I request the "2nd Tuesday") you will get values that are improperly offset by one week for no apparent reason. This has been documented as bug #43452 and is still currently unresolved. Just be careful if you're relying on this function for that purpose; you're going to get incorrect values until this gets fixed!

http://bugs.php.net/bug.php?id=43452
shem_lexluger at yahoo.com
14-Jul-2008 02:44
Assuming a week starts on Monday. To calculate the week number of the current date starting from a specified date, use this function:

<?php
function weekcounter($start_date)
{
  
$start_date = strtotime($start_date);
  
$today = strtotime(date('d-m-Y'));

  
$week = 1;
   while(
$start_date < $today) {
   
$start_date = strtotime('next Monday', $start_date);
   
$week++;
   }

   return
$week;
}
?>

Example:
//now = 14-07-2008
echo weekcounter('01-07-2008'); //prints 3
echo weekcounter('01-06-2008'); //prints 8 instead of 7; because 1st jun is a Sunday so it is week 1 and 2nd june is week 2. Feel free to tweak.
enkrs
01-Jul-2008 09:48
It is worth noting, that strtotime() accepts ISO week date format (for example "2008-W27-2" is Tuesday of week 27 in 2008), so it can be easily used to get the date of a given week number.

<?php
function week($year, $week)
{
   
$from = date("Y-m-d", strtotime("{$year}-W{$week}-1")); //Returns the date of monday in week
   
$to = date("Y-m-d", strtotime("{$year}-W{$week}-7")); //Returns the date of sunday in week
   
return "Week {$week} in {$year} is from {$from} to {$to}.";
}
echo
week(2008,27);
//Returns: Week 27 in 2008 is from 2008-06-30 to 2008-07-06.
?>
highermind.org
25-Jun-2008 04: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.

<?php
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 09:59
When using a custom timestamp and adding a day to it, this works:

strtotime("20080601 +1 day")

this does not:

strtotime("20080601") + strtotime("+1 day")

that's because "+1 day" is another way to say the timestamp corresponding to tomorrow as of right now.

If you do it the wrong way, you'll end up with really bizarre dates in your loops. I was going from 20080601 to 19101019 to 19490412. What fun it was figuring that out. :)
Dieter D
20-Jun-2008 03: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 07:10
BEWARE:  Someone thought this was a good idea...

$t = strtotime('2008-00-14'); // == 1197590400
$d = date("d-m-Y", $t); // == 14-12-2007

I am not sure when this function EVER returns false but its obviously not when the dates incorrect.
timstamp.co.uk
10-Jun-2008 05:31
When using DB2 as an ODBC database source, the timestamps returned are in format "YYYY-MM-DD HH:MM:SS.mmmmmm" (m being microseconds).

Given that strtotime($str) is only accurate down to the second, you need to remove the microseconds from the string for it to work in strtotime.
For example:
<?php
$date
= "2008-06-10 16:15:50.123456"; //as returned by DB2 SQL
$date = substr($date, 0, 19); //chop off the last 7 characters
//thus
$date == 1213110950;
//and
date('Y-m-d H-i-s', $date) == "2008-06-10 16:15:50";
?>

Note that if you wish to preserve the microseconds, you will need to do so before you chop them off of the string, but you don't need to include them or even pad timestamps with zeros when inserting them back into DB2.
richard at happymango dot me dot uk
10-Jun-2008 01: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 12: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
01-Jun-2008 04:56
Someone already reported an issue with finding the next month on the 31st of a month goes to two months down (essentially the next month with 31 days). There's a workaround for PHP 5.3+ here:

http://bugs.php.net/bug.php?id=44073

If you don't have 5.3 like me (and I can't update it) this code works:

<?php

// On the 31st of May:
strtotime("+1 month"); // Outputs July

strtotime("+1 month", strtotime(date("F") . "1")); // Outputs June

?>

In Engish: Figure out next month relative to the first of this month (date ("F") returns current month).
php dot net at dubaifaqs dot com
09-May-2008 09:08
Booyah! $time containing only numeric and space characters results in unexpected output (at least on Win2K server, not checked with linux).

<?php

echo date('d F Y', strtotime('2007')); // today's date (09 May 2008) displayed
echo date('d F Y', strtotime('01 2007')); // Warning: date(): Windows does not support dates prior to midnight (00:00:00), January 1, 1970
echo date('d F Y', strtotime('01 01 2007')); // same warning
echo date('d F Y', strtotime('01 Jan 2007')); // 01 January 2007

?>

No bug report submitted, I don't know enough about php and servers to know if this is expected behaviour or not.
Jo H
07-May-2008 11: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)
till at pralinenschachtel dot de
01-May-2008 10: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;

}
?>
brian at diamondsea dot com
14-Apr-2008 04:53
I am having problems with the timhavens's <i>dates_betweeen_dates()</i> script not returning proper output for calls like:

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

<?php
/*
 *  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 09:26
It suggests prior to v4.4, "next XXXday" is incorrectly calculated as "+2", and that a remedy is "+1".

"+1" will result in an incorrect date. The solution should actually read just enter "xxxday" as the offset - not "+1 xxxDay"
Raymond Irving
26-Mar-2008 04: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 02: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.

<?php
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);
      
$date2date("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;
}
?>
Anonymous
04-Mar-2008 01: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 07: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... 

<?php
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("+1 day ", 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;
}
?>

[EDIT by danbrown AT php DOT net: Applied user-provided fix to this code.]
php at bucksvsbytes dot com
24-Feb-2008 03:22
The phrase "about any English textual datetime description" is misleading. The GNU Date Input Formats syntax is actually quite limited and, counterintuitively, some commonly used formats result in incorrect or invalid dates that confound users. In particular, the commonly used m-d-y format does not work. 2-23-08 is invalid!

It would be helpful to list the allowed date formats in the documentation rather than just by reference to the GNU docs:

for numeric months the only valid formats are:
y-m-d
m/d/y
m/d

for text months the only valid formats are:
d month y
d month
month d y
d-month-y
month d

Although the GNU doc says leading zeros are required for numbers less than 10 this does not seem to be necessary (5/7/8 is same as 05/07/08).
ecziegler at gmail
21-Feb-2008 01: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
16-Feb-2008 05: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
03-Feb-2008 02: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 10:15
I found some different behaviors between PHP 4 and PHP 5.  I have tested this on just two versions: PHP Version 5.2.3-1ubuntu6.3 and PHP Version 4.3.10-22.

Example 1:
<?php
$ts2
= strtotime("1st Thursday", $ts1)
var_dump($ts2)
// this works in PHP 4
// PHP 5 dumps bool(false)
?>

Example 2:
<?php
$ts2
= strtotime("first Thursday", $ts1)
var_dump($ts2)
// this works in PHP 4
// also works in PHP 5
?>
enyone
31-Jan-2008 11:01
More intelligent function to switch between months:

<?php
   
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 02:35
This code is for relative dates similar to the add date functionality that C# has.  It allows for negative values to substract dates.

<?php
/*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 02:56
As with each of the time-related functions, and as mentioned in the time() notes, strtotime() is affected by the year 2038 bug on 32-bit systems:

<?php
   
echo strtotime('13 Dec 1901 20:45:51'); // false
   
echo strtotime('13 Dec 1901 20:45:52'); // -2147483648

   
echo strtotime('19 Jan 2038 03:14:07'); // 2147483647
   
echo strtotime('19 Jan 2038 03:14:08'); // false
?>
xini [at] gmx [dot] de
10-Dec-2007 05:21
Be careful with spaces between the "-" and the number in the argument, for some PHP-installations...

<?php
strtotime
("- 1 day"// ...with space - will ADD a day
strtotime("-1 day"// ...works perfect
?>
andrew dot myers at civicwifi dot com
05-Dec-2007 07:42
Here is a list of differences between PHP 4 and PHP 5 that I have found
(specifically PHP 4.4.2 and PHP 5.2.3).

<?php

$ts_from_nothing
= strtotime();
var_dump($ts_from_nothing);
// PHP 5
//    bool(false)
//    WARNING: Wrong parameter count...
// PHP 4
//    NULL
//    WARNING: Wrong parameter count...

// remember that unassigned variables evaluate to NULL
$ts_from_null = strtotime($null);
var_dump($ts_from_null)...
// PHP 5
//    bool(false)
//    throws a NOTICE: Undefined variable
// PHP 4
//    current time
//    NOTICE: Undefined variable $null...
//    NOTICE: Called with empty time parameter...

$ts_from_empty = strtotime("");
var_dump($ts_from_empty);
// PHP 5
//    bool(false)
// PHP 4
//    current time
//    NOTICE: Called with empty time parameter

$ts_from_bogus = strtotime("not a date");
var_dump($ts_from_bogus);
// PHP 5
//    bool(false)
// PHP 4
//    -1

?>
php at bucksvsbytes dot com
05-Dec-2007 02:35
I get what appear to be incorrect results from
<?php
//$yr=4-digit year
strtotime($yr);
?>
a) for $yr from 1960-1999, function returns timestamp of current date/time in $yr
b) for other $yr from xx60-xx99, function returns false as expected.
c) for $yr from xx00-xx59, function returns current timestamp.
Hayley Watson
25-Nov-2007 10:38
As for the cases which Beat notes as "CORRECT": 23:59:59 30 September is less than an hour earlier than 00:00:00 1 October - and by happenstance Cent