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.
strtotime
(PHP 4, PHP 5)
strtotime — Parse about any English textual datetime description into a Unix timestamp
Description
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
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.
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.
strtotime
09-May-2008 12:08
07-May-2008 02: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)
01-May-2008 01: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 ;)
01-May-2008 01: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;
}
?>
30-Apr-2008 07:50
Get the first day of the month:
<?php
$time = time();
echo date('m/d/Y', strtotime('1 '.date('F', $time).' '.date('Y', $time)));
?>
22-Apr-2008 08: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;
}
14-Apr-2008 07: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;
}
?>
27-Mar-2008 01: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"
25-Mar-2008 08: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
12-Mar-2008 06: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;
}
11-Mar-2008 03: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"));
?>
04-Mar-2008 02: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.
04-Mar-2008 04: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?
02-Mar-2008 10: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;
}
23-Feb-2008 06: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).
21-Feb-2008 04: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'))));
15-Feb-2008 08: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);
}
?>
02-Feb-2008 05: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
)
31-Jan-2008 01: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
?>
31-Jan-2008 02: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 );
}
29-Jan-2008 05: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;
}
21-Jan-2008 05:56
As with each of the time-related functions, and as mentioned in the time() notes, strtotime() is affected by the year 2038 bug on 32-bit systems:
<?php
echo strtotime('13 Dec 1901 20:45:51'); // false
echo strtotime('13 Dec 1901 20:45:52'); // -2147483648
echo strtotime('19 Jan 2038 03:14:07'); // 2147483647
echo strtotime('19 Jan 2038 03:14:08'); // false
?>
10-Dec-2007 08:21
Be careful with spaces between the "-" and the number in the argument, for some PHP-installations...
<?php
strtotime("- 1 day") // ...with space - will ADD a day
strtotime("-1 day") // ...works perfect
?>
05-Dec-2007 10: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
?>
04-Dec-2007 05:35
I get what appear to be incorrect results from
<?php
//$yr=4-digit year
strtotime($yr);
?>
a) for $yr from 1960-1999, function returns timestamp of current date/time in $yr
b) for other $yr from xx60-xx99, function returns false as expected.
c) for $yr from xx00-xx59, function returns current timestamp.
25-Nov-2007 01: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.
22-Nov-2007 09: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.
15-Nov-2007 04:44
I had a whole bunch of trouble with a calendar where I was trying to create recurring events. The problem was that for certain dates, the 'second friday' of the month would work and would not. There are a lot of flaws with the way I was processing, so I wrote this instead of using strtotime() to solve my issue.
This solves the simple problem of finding the x weekday of any month. (first friday of 11-2007 or last tuesday of Dec, 1962)
<?php
function get_day( $describer, $weekday, $reference_date ) { //$reference_date format = m-Y
$d = explode('-',$reference_date);
switch ($describer) {
case 'first': $offset = get_day_offset($reference_date, $weekday); break;
case 'second': $offset = get_day_offset($reference_date, $weekday) + 7; break;
case 'third': $offset = get_day_offset($reference_date, $weekday) + 14; break;
case 'fourth': $offset = get_day_offset($reference_date, $weekday) + 21; break;
case 'last': $reference_date = ($d[0]+1).'-'.($d[1]); $d = explode('-',$reference_date);
$offset = get_day_offset($reference_date, $weekday) - 7; break;
}
$r = mktime( 0, 0, 0, $d[0], 1+$offset, $d[1] );
return $r; //returns timestamp format
}
function get_day_offset( $anchor , $target ) { //$anchor format = m-Y
$ts = explode('-',$anchor);
$ts = mktime(0,0,0,$ts[0],'01',$ts[1]);
$anchor = date("w",$ts);
$target = strtolower($target);
$days = array( 'sunday'=>0, 'monday'=>1, 'tuesday'=>2, 'wednesday'=>3, 'thursday'=>4, 'friday'=>5, 'saturday'=>6 );
$offset = $days[$target] - $anchor;
if ($offset<0) $offset+=7;
return $offset; //returns 0-6 for use in get_day();
}
$date1 = get_day("second", "saturday", "12-2007");
$date2 = get_day("last", "friday", "11-2007");
echo "Second Saturday of December, 2007: ".date("m-d-Y", $date1)."<br>";
echo "Last Friday of November, 2007: ".date("m-d-Y", $date2)."<br>";
?>
Outputs:
Second Saturday of December, 2007: 12-08-2007
Last Friday of November, 2007: 11-30-2007
15-Nov-2007 01:53
Not sure why the ordinals are not on this page.
However I was trying to subtract some hours from a certain date.
echo date('m-d-Y', strtotime("- x hours"));
This code would not work. Instead it would add two hours.
You must use the ordinal ago.
echo date('m-d-Y', strtotime("x hours ago"));
Will return the right date.
Here are the ordinals.
Relative and Ordinal Specifiers:
ago: past time relative to now; such as "24 hours ago"
tomorrow: 24 hours later than the current date and time
yesterday: 24 hours earlier than the current date and time
today: the current date and time
now: the current date and time
last: modifier meaning "the preceding"; for example, "last tuesday"
this: the given time during the current day or the next occurrence of the given time; for example, "this 7am" gives the timestamp for 07:00 on the current day, while "this week" gives the timestamp for one week from the current time
next: modifier meaning the current time value of the subject plus one; for example, "next hour"
first: ordinal modifier, esp. for months; for example, "May first" (actually, it's just the same asnext)
third: see first (note that there is no "second" for ordinality, since that would conflict with thesecond time value)
fourth: see first
fifth: see first
sixth: see first
seventh: see first
eighth: see first
ninth: see first
tenth: see first
eleventh: see first
twelfth: see first
06-Nov-2007 01: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.
01-Oct-2007 03:41
Here the workaround to the bug of strtotime() found in my previous comment on finding the exact date and time of "3 months ago of last second of this year", using mktime() properties on dates instead of strtotime(), and which seems to give correct results:
<?php
// check for equivalency
$basedate = strtotime("31 Dec 2007 23:59:59");
$timedate = mktime( 23, 59, 59, 1, 0, 2008 );
echo "$basedate $timedate "; // 1199141999 1199141999 : SO THEY ARE EQUIVALENT
// workaround, as mktime knows to handle properly offseted dates:
$date1 = mktime( 23, 59, 59, 1 - 3, 0, 2008 );
echo date("j M Y H:i:s", $date1); // 30 Sep 2007 23:59:59 CORRECT
?>
01-Oct-2007 01:36
Some surprisingly wrong results (php 5.2.0): date and time seem not coherent:
<?php
// Date: Default timezone Europe/Berlin (which is CET)
// date.timezone no value
$basedate = strtotime("31 Dec 2007 23:59:59");
$date1 = strtotime("-3 months", $basedate);
echo date("j M Y H:i:s", $date1); // 1 Oct 2007 23:59:59 WRONG
$basedate = strtotime("31 Dec 2007 23:59:59 CET");
$date1 = strtotime("-3 months", $basedate);
echo date("j M Y H:i:s", $date1); // 1 Oct 2007 23:59:59 WRONG
$basedate = strtotime("31 Dec 2007 23:59:59 GMT");
$date1 = strtotime("-3 months", $basedate);
echo date("j M Y H:i:s", $date1); // 1 Oct 2007 00:59:59 CORRECT
$basedate = strtotime("31 Dec 2007 22:59:59 GMT");
$date1 = strtotime("-3 months", $basedate);
echo date("j M Y H:i:s", $date1); // 1 Oct 2007 23:59:59 WRONG AGAIN
$basedate = strtotime("31 Dec 2007 00:00:00 GMT");
$date1 = strtotime("-3 months", $basedate);
echo date("j M Y H:i:s", $date1); // 1 Oct 2007 01:00:00 CORRECT
$basedate = strtotime("31 Dec 2007 00:00:00 CET");
$date1 = strtotime("-3 months", $basedate);
echo date("j M Y H:i:s", $date1); // 1 Oct 2007 00:00:00 WRONG AGAIN
$basedate = strtotime("31 Dec 2007 00:00:01");
$date1 = strtotime("-3 months", $basedate);
echo date("j M Y H:i:s", $date1); // 1 Oct 2007 00:00:01 WRONG AGAIN
?>
14-Sep-2007 02:12
PHP 5.1.0 and above might overcome the limitation of parsing dates earlier than 1970, but they still do it at a much slower pace (About 0.5 seconds). Just a note for anyone trying to use this function for this purpose.
02-Sep-2007 07:33
Another inconsistency between versions:
print date('Y-m-d H:i:s', strtotime('today')) . "\n";
print date('Y-m-d H:i:s', strtotime('now')) . "\n";
In PHP 4.4.6, "today" and "now" are identical, meaning the current timestamp.
In PHP 5.1.4, "today" means midnight today, and "now" means the current timestamp.
27-Aug-2007 05:40
I am thinking this function may have a bug in it. Can anyone explain why strtotime when parsing two RSS-2 newfeeds with ISO-2822 timestamps for the pubDate can give true in the first case and false in the second case?
Wed, 22 Aug 2007 21:23:51 -0500 (This works)
Mon, 27 Aug 2007 12:47:06 +0000 (This returns false)
I am using PHP 5.1.2.
15-Aug-2007 07:42
@smartalco:
Since the first day of a month is always the first (unless I missed something in History), you could save yourself some overhead from the second strtotime() by forcing the day manually:
<?php
echo date('l, F jS Y', strtotime('August 1 2007'));
// Outputs "Wednesday, August 1st 2007"
?>
While it's a relatively minor performance difference in a small script, it would be compounded significantly in larger applications or loops.
26-Jul-2007 09:19
a simple way to find the first day of a month
<?php
echo date('l, F jS Y', strtotime("first day", strtotime("August 0 2007")));
?>
result:
Wednesday, August 1st 200
19-Jul-2007 06:13
A major difference in behavior between PHP4x and newer 5.x versions is the handling of "illegal" dates: With PHP4, strtotime("2007/07/55") gave a valid result that could be used for further calculations.
This does not work anymore at PHP5.xx (here: 5.2.1), instead something like strtotime("$dayoffset_relative_to_today days","2007/07/19") is to be used.
07-Jul-2007 10:47
when using strtotime("wednesday"), you will get different results whether you ask before or after wednesday, since strtotime always looks ahead to the *next* weekday.
strtotime() does not seem to support forms like "this wednesday", "wednesday this week", etc.
the following function addresses this by always returns the same specific weekday (1st argument) within the *same* week as a particular date (2nd argument).
function weekday($day="", $now="") {
$now = $now ? $now : "now";
$day = $day ? $day : "now";
$rel = date("N", strtotime($day)) - date("N");
$time = strtotime("$rel days", strtotime($now));
return date("Y-m-d", $time);
}
example use:
weekday("wednesday"); // returns wednesday of this week
weekday("monday, "-1 week"); // return monday the in previous week
ps! the ? : statements are included because strtotime("") without gives 1 january 1970 rather than the current time which in my opinion would be more intuitive...
30-Jun-2007 07:54
To calculate the last Friday in the current month, use strtotime() relative to the first day of next month:
<?php
$lastfriday=strtotime("last Friday",mktime(0,0,0,date("n")+1,1));
?>
If the current month is December, this capitalises on the fact that the mktime() function correctly accepts a month value of 13 as meaning January of the next year.
31-May-2007 08:10
Note about strtotime() when trying to figure out the NEXT month...
strtotime('+1 months'), strtotime('next month'), and strtotime('month') all work fine in MOST circumstances...
But if you're on May 31 and try any of the above, you will find that 'next month' from May 31 is calculated as July instead of June....
12-May-2007 08:41
One more difference between php 4 and 5 (don't know when they changed this) but the string 15 EST 5/12/2007 parses fine with strtotime in php 4, but returns the 1969 date in php 5. You need to add :00 to make it 15:00 so php can tell those are hours. There's no change in php 4 when you do this.
07-Apr-2007 06:31
This function inputs a date sting and outputs an integer that is the internal representation of days that spreadsheets use. Post this value into a cell, then format that cell as a Date.
function conv_to_xls_date($Date) {
// Returns the Excel/Calc internal date integer from either an ISO date YYYY-MM-DD or MM/DD/YYYY formats.
return (int) (25569 + (strtotime("$Date 12:00:00") / 86400));
}
example:
$Date = "04-07-2007";
$Days = conv_to_xls_date($Date);
$Days will contain 39179
SQL datetime columns have a much wider range of allowed values than a UNIX timestamp, and therefore this function is not safe to use to convert a SQL datetime column to something usable in PHP4. Year 9999 is the limit for MySQL, which obviously exceeds the UNIX timestamp's capacity for storage. Also, dates before 1970 will cause the function to fail (at least in PHP4, don't know about 5+), so for example my boss' birthday of 1969-08-11 returned FALSE from this function.
[red. The function actually supports it since PHP 5.1, but you will need to use the new object oriented methods to use them. F.e:
<?php
$date = new DateTime('1969-08-11');
echo $date->format('m d Y');
?>
]
09-Feb-2007 12:29
Regarding the "NET" thing, it's probably parsing it as a time-zone. If you give strtotime any timezone string (like PST, EDT, etc.) it will return the time in that time-zone.
In any case, you shouldn't use strtotime to validate dates. It can and will give incorrect results. As just one shining example:
Date: 05/01/2007
To most Americans, that's May 1st, 2007. To most Europeans, that's January 5th, 2007. A site that needs to serve people around the globe cannot use strtotime to validate or even interpret dates.
The only correct way to parse a date is to mandate a format and check for that specific format (preg_match will make your life easy) or to use separate form fields for each component (which is basically the same thing as mandating a format).
16-Jan-2007 02:47
A hint not to misunderstand the second parameter:
The parameter "[, int now]" is only used for strings which describe a time difference to another timestamp.
It is not possible to use strtotime() to calculate a time difference by passing an absolute time string, and another timestamp to compare to!
Correct:
$day_before = strtotime("+1 day", $timestamp);
# result is a timestamp relative to another
Wrong:
$diff = strtotime("2007-01-15 11:40:00", time());
# result it the timestamp for the date in the string;
# because the string contains an absolute date and time,
# the second parameter is ignored!
# instead, use:
$diff = time() - strtotime("2007-01-15 11:40:00");
05-Oct-2006 12:02
The following might produce something different than you might expect:
<?php
echo date('l, F jS Y', strtotime("third wednesday", strtotime("2006-11-01"))) . "<br>";
echo date('l, F jS Y', strtotime("third sunday", strtotime("2006-01-01")));
?>
Produces:
Wednesday, November 22nd 2006
Sunday, January 22nd 2006
The problem stems from strtotime when the requested day falls on the date passed to strtotime. If you look at your calendar you will see that they should return:
Wednesday, November 15th 2006
Sunday, January 15th 2006
Because the date falls on the day requested it skips that day.
11-May-2006 03:18
The GNU manual page has moved, the new address is
http://www.gnu.org/software/shishi/manual/html_node/Date-input-formats.html
11-Apr-2006 04:08
I have had some inconsistancies that was not immediately evident and suggested that strtotime treated my date formats in different ways.
I had trouble with the date format: d/m/Y
I eliminated the inconsistancies by changing the date format to one where (i guess) php does not try and guess the right format. In my case I changed it to the format (d-M-Y) in which case it worked.
Example when trying to find a person's age where:
//$date in format (d/m/Y) was inconsistant but fixed when in format (d-M-Y), e.g. (01-January-2001)
$age = (time() - strtotime($date))/(60*60*24*360);
24-Jan-2006 10:18
It looks like in the latest release of PHP 5.1, when passing to strtotime this string "12/32/2005", it will now return the date "12/31/1969". (The previous versions would return "1/1/2006".)
17-Jan-2006 04:32
Regarding the previous post on strtotime() being used to convert mysql datetime strings, I agree that this is not widely realized.
Part of the reason for this is that it is only a relatively recent addition. Prior to PHP 5.0, though it might have been an earlier version, strtotime() would return -1 on a mysql datetime string.
If you're on a server that doesn't have a recent PHP version test your result before assuming this one works.
11-Jan-2006 08:13
I'm posting these here as I believe these to be design changes, not bugs.
For those upgrading from PHP 4 to PHP 5 there are a number of things that are different about strtotime that I have NOT seen documented elsewhere, or at least not as clearly. I confirmed these with two separate fresh installations of PHP 4.4.1 and PHP 5.1.1.
1) Given that today is Tuesday: PHP4 "next tuesday" will return today. PHP5 "next tuesday" will actually return next tuesday as in "today +1week". Note that behavior has NOT changed for "last" and "this". For the string "last tuesday" both PHP4 and PHP5 would return "today -1week". For the string "this tuesday" both PHP4 and PHP5 would return "today".
2) You cannot include a space immediately following a + or - in PHP 5. In PHP4 the string "today + 1 week" works great. in PHP5 the string must be "today +1 week" to correctly parse.
3) (Partially noted in changelog.) If you pass php4 a string that is a mess ("asdf1234") it will return -1. If you in turn pass this to date() you'll get a warning like: Windows does not support dates prior to midnight. This is pretty useful for catching errors in your scripts. In PHP 5 strtotime will return FALSE which causes date() to return 12/31/69. Note that this is true of strings that might appear right such as "two weeks".
4) (Partially noted in changelog.) If you pass php4 an empty string it will error out with a "Notice: strtotime(): Called with empty time parameter". PHP5 will give no notice and return the current date stamp. (A much preferred behavior IMO.)
5) Some uppercase and mixed-case strings no longer parse correctly. In php4 "Yesterday" would parse correctly. In php5 "Yesterday" will return the infamous 1969 date. This is also true of Tomorrow and Today. [Red. This has been fixed in PHP already]
6. The keyword "previous" is supported in PHP5. (Finally!)
Good luck with your upgrades. :)
-Will
26-Oct-2005 03:52
Note that strtotime('next month') will return 2 months from now, which may not be what you expect. strtotime('month') will do 1 month.
06-Oct-2005 02:34
Note strtotime() in PHP 4 does not support fractional seconds.
See http://bugs.php.net/bug.php?id=28717 especially if you happen to swap to ODBC for MS SQL Server and wonder what's happened!
28-Sep-2005 08: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"]
28-Aug-2005 06: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
14-Aug-2005 11:49
When using multiple negative relative items, the result might be a bit unexpected:
<?php
$basedate = strtotime("15 Aug 2005 10:15:00");
$date1 = strtotime("-1 day 2 hours", $basedate);
$date2 = strtotime("-1 day -2 hours", $basedate);
echo date("j M Y H:i:s", $date1); // 14 Aug 2005 12:15:00
echo date("j M Y H:i:s", $date2); // 14 Aug 2005 08:15:00
?>
The minus sign has to be added to every relative item, otherwise they are interpreted as positive (increase in time). Other possibility is to use "1 day 2 hours ago".
15-Jul-2005 02: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
12-Jul-2005 04:13
relative dates..
echo date('d F Y', strtotime('last monday', strtotime('15 July 2005'))); // 11th
echo "<br>";
echo date('d F Y', strtotime('this monday', strtotime('15 July 2005'))); // 18th
echo "<br>";
echo date('d F Y', strtotime('next monday', strtotime('15 July 2005'))); // 25th
28-Jun-2005 05:14
This is an easy way to calculate the number of months between 2 dates (including the months in which the dates are themselves).
<?
$startDate = mktime(0,0,0, 6, 15, 2005);
$stopDate = mktime(0,0,0, 10, 8, 2006);
$nrmonths = ((idate('Y', $stopDate) * 12) + idate('m', $stopDate)) - ((idate('Y', $startDate) * 12) + idate('m', $startDate));
?>
Results in $nrmonths = 16.
09-May-2005 01:49
Here's a quick one-line function you can use to get the time difference for relative times. But default, if you put in a relative time (like "1 minute"), you get that relative to the current time. Using this function will give you just the time difference in seconds:
<?php function relative_time( $input ) { return strtotime($input) - time(); } ?>
For example "1 minute" will return 60, while "30 seconds ago" will return -30
Valid relative time formats can be found at http://www.gnu.org/software/tar/manual/html_chapter/tar_7.html#SEC115
22-Apr-2005 09:59
If you strtotime the epoch (Jan 1 1970 00:00:00) you will usually get a value, rather than the expected 0. So for example, if you were to try to use the epoch to calculate the difference in times (strtotime(Jan 1 1970 21:00:00)-strtotime(Jan 1 1970 20:00:00) for example) You get a value that depends strongly upon your timezone. If you are in EST for example, the epoch is actually shifted -5 to YOUR epoch is Jan 1 1970 19:00:00) In order to get the offset, simply use the following call to report the number of seconds you are away from the unix epoch. $offset=strtotime("1970-01-01 00:00:00"); Additionally, you can append GMT at the end of your strtotime calls so save yourself the trouble of converting relative to timezone.
I ran into the same problem with "last" as gabrielu at hotmail dot com (05-Apr-2005 10:45) when using strtotime() with getdate(). My only guess is that it has to do with daylight savings time as it seemed to be ok for most dates except those near the first Sunday in April and last Sunday in October.
I used strftime() with strtotime() and that gave me the result I was looking for.
05-Apr-2005 09:45
While working on an employee schedule application I noticed an issue with using strtotime('last...'). I ran tests on each weekday for each week within a year and noticed inconsistencies while using:
date('m/d/Y', strtotime('last Wednesday', '2005-04-05'))
Most calculations of the 'last Wednesday' for each week calculated accordingly however I noticed a problem with several dates, one being '04/05/2005' (April 5th 2005).
date('m/d/Y', strtotime('last Wednesday', '2005-04-05'))
The above should have returned '03/30/2005'. Instead, it returned '03/29/2005'. I don't understand why the function is returning this value. Regardless, my solution:
date('m/d/Y', strtotime('-1 week' ,strtotime('Wednesday', '2005-04-05')))
08-Dec-2004 08: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.
19-Aug-2004 06:38
After a slight moment of frustration, and finding that I'm not the only one with this problem (see http://bugs.php.net/bug.php?id=28088 - it's a known bug) I decided to write a short workaround for dealing with the 00 hour problem.
The problem only seems to occur when inputting strings such as '08/20/2004 0047' and NOT '08/20/2004 00:47'. Hence, my fix:
<?php
$your_value ( preg_replace ('#^(\d+/\d+/?\d{2,4} )(00)(\d{2})$#', '$1$2:$3', $your_value() ));
?>
06-Apr-2004 11:39
I neglected to include the solution in my last post for using strtotime() with date-time data stored in GMT. Append the string "GMT" to all of your datetimes pulled from MySQL or other database that store date-times in the format "yyyy-mm-dd hh:ii:ss" just prior to converting them to a unix timestamp with strtotime(). This will ensure you get a valid GMT result for times during daylight savings.
EXAMPLE:
<?php
$date_time1 = strtotime("2004-04-04 02:00:00"); // returns bad value -1 due to DST
$date_time2 = strtotime("2004-04-04 02:00:00 GMT"); // works great!
?>
01-Jan-2004 03: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.
