Beruflich Dokumente
Kultur Dokumente
PHP Manual
Function Reference
Date and Time Related Extensions
Date/Time
Date/Time Functions
checkdate
date_ add
date_ create_ from_ format
date_ create
date_ date_ set
date_ default_ timezone_ get
date_ default_ timezone_ set
date_ diff
date_ format
date_ get_ last_ errors
date_ interval_ create_ from_ date_ string
date_ interval_ format
date_ isodate_ set
date_ modify
date_ offset_ get
date_ parse_ from_ format
date_ parse
date_ sub
date_ sun_ info
date_ sunrise
date_ sunset
date_ time_ set
date_ timestamp_ get
date_ timestamp_ set
date_ timezone_ get
date_ timezone_ set
date
getdate
gettimeofday
gmdate
gmmktime
gmstrftime
idate
localtime
microtime
mktime
strftime
strptime
strtotime
time
timezone_ abbreviations_ list
timezone_ identifiers_ list
timezone_ location_ get
timezone_ name_ from_ abbr
timezone_ name_ get
timezone_ offset_ get
timezone_ open
timezone_ transitions_ get
timezone_ version_ get
getdate date_timezone_set
date
(PHP 4, PHP 5)
Report a bug
Description
Returns a string formatted according to the given format string using the given integer
timestamp or the current time if no timestamp is given. In other words, timestamp is optional
and defaults to the value of time().
Report a bug
Parameters
format
The format of the outputted date string. See the formatting options below. There are also
several predefined date constants that may be used instead, so for example DATE_RSS
contains the format string 'D, d M Y H:i:s'.
Unrecognized characters in the format string will be printed as-is. The Z format will
always return 0 when using gmdate().
Note:
Since this function only accepts integer timestamps the u format character is only
useful when using the date_format() function with user based timestamps created
with date_create().
timestamp
The optional timestamp parameter is an integer Unix timestamp that defaults to the
current local time if a timestamp is not given. In other words, it defaults to the value of
time().
Report a bug
Return Values
Returns a formatted date string. If a non-numeric value is used for timestamp, FALSE is returned
and an E_WARNING level error is emitted.
Report a bug
Errors/Exceptions
Every call to a date/time function will generate a E_NOTICE if the time zone is not valid, and/or a
E_STRICT or E_WARNING message if using the system settings or the TZ environment variable.
See also date_default_timezone_set()
Report a bug
Changelog
Version Description
5.1.0 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). However, before PHP 5.1.0 this range
Version Description
was limited from 01-01-1970 to 19-01-2038 on some systems (e.g. Windows).
5.1.0 Now issues the E_STRICT and E_NOTICE time zone errors.
There are useful constants of standard date/time formats that can be used to specify the
5.1.1
format parameter.
Report a bug
Examples
<?php
// set the default timezone to use. Available since PHP 5.1
date_default_timezone_set('UTC');
// Prints something like: Monday
echo date("l");
// Prints something like: Monday 8th of August 2005 03:12:46 PM
echo date('l jS \of F Y h:i:s A');
// Prints: July 1, 2000 is on a Saturday
echo "July 1, 2000 is on a " . date("l", mktime(0, 0, 0, 7, 1, 2000));
/* use the constants in the format parameter */
// prints something like: Mon, 15 Aug 2005 15:12:46 UTC
echo date(DATE_RFC822);
// prints something like: 2000-07-01T00:00:00+00:00
echo date(DATE_ATOM, mktime(0, 0, 0, 7, 1, 2000));
?>
You can prevent a recognized character in the format string from being expanded by escaping it
with a preceding backslash. If the character with a backslash is already a special sequence, you
may need to also escape the backslash.
<?php
// prints something like: Wednesday the 15th
echo date("l \\t\h\e jS");
?>
It is possible to use date() and mktime() together to find dates in the future or the past.
<?php
$tomorrow = mktime(0, 0, 0, date("m") , date("d")+1, date("Y"));
$lastmonth = mktime(0, 0, 0, date("m")-1, date("d"), date("Y"));
$nextyear = mktime(0, 0, 0, date("m"), date("d"), date("Y")+1);
?>
Note:
This can be more reliable than simply adding or subtracting the number of seconds in a day or
month to a timestamp because of daylight saving time.
Some examples of date() formatting. Note that you should escape any other characters, as any
which currently have a special meaning will produce undesirable results, and other characters
may be assigned meaning in future PHP versions. When escaping, be sure to use single quotes to
prevent characters like \n from becoming newlines.
<?php
// Assuming today is March 10th, 2001, 5:16:18 pm, and that we are in the
// Mountain Standard Time (MST) Time Zone
$today = date("F j, Y, g:i a"); // March 10, 2001, 5:16 pm
$today = date("m.d.y"); // 03.10.01
$today = date("j, n, Y"); // 10, 3, 2001
$today = date("Ymd"); // 20010310
$today = date('h-i-s, j-m-y, it is w Day'); // 05-16-18, 10-03-01, 1631 16
18 6 Satpm01
$today = date('\i\t \i\s \t\h\e jS \d\a\y.'); // it is the 10th day.
$today = date("D M j G:i:s T Y"); // Sat Mar 10 17:16:18 MST 200
1
$today = date('H:m:s \m \i\s\ \m\o\n\t\h'); // 17:03:18 m is month
$today = date("H:i:s"); // 17:16:18
?>
To format dates in other languages, you should use the setlocale() and strftime() functions
instead of date().
Report a bug
Notes
Note:
To generate a timestamp from a string representation of the date, you may be able to use
strtotime(). Additionally, some databases have functions to convert their date formats into
timestamps (such as MySQL's » UNIX_TIMESTAMP function).
Tip
See Also
getdate date_timezone_set
<?php
function dateafter ( $a )
{
$hours = $a * 24;
$added = ($hours * 3600)+time();
$days = date("l", $added);
$month = date("F", $added);
$day = date("j", $added);
$year = date("Y", $added);
$result = "$day $month $year - $days";
return ($result);
}
echo dateafter("10");
//this will shows the data of ten days after.
// if today is 19 December 2010, Sunday, the page prints : 29 December 2010 -
Wednesday.
?>
ghotinet 13-Dec-2010 06:06
Most spreadsheet programs have a rather nice little built-in function called
NETWORKDAYS to calculate the number of business days (i.e. Monday-Friday,
excluding holidays) between any two given dates. I couldn't find a simple way
to do that in PHP, so I threw this together. It replicates the functionality
of OpenOffice's NETWORKDAYS function - you give it a start date, an end date,
and an array of any holidays you want skipped, and it'll tell you the number
of business days (inclusive of the start and end days!) between them.
The function could certainly be made much more powerful, to allow you to set
different days to be ignored (e.g. "skip all Fridays and Saturdays but include
Sundays") or to set up dates that should always be skipped (e.g. "skip July
4th in any year, skip the first Monday in September in any year"). But that's
a project for another time.
<?php
// Find the ISO-8601 day of the week for the two dates.
$sd = date("N", $s);
$ed = date("N", $e);
// Iterate through the array of holidays. For each holiday between the
start and end dates that isn't a Saturday or a Sunday, remove one day.
foreach ($holidays as $h) {
$h = strtotime($h);
if ($h > $s && $h < $e && date("N", $h) < 6)
$nwd--;
}
?>
Or, if you just want to know how many work days there are in any given year,
here's a quick function for that one:
<?php
function workdaysinyear($y) {
$j1 = mktime(0,0,0,1,1,$y);
if (date("L", $j1)) {
if (date("N", $j1) == 6)
return 260;
elseif (date("N", $j1) == 5 or date("N", $j1) == 7)
return 261;
else
return 262;
}
else {
if (date("N", $j1) == 6 or date("N", $j1) == 7)
return 260;
else
return 261;
}
}
?>
iphraimov at gmail dot com 08-Dec-2010 04:15
Here is simple function to generate date selection, useful for admin
panels ....
<?php
public static function dateRange($fmt = 'j-n-Y', $sep='+') {
$current_time = time();
$year = date('Y',$curr_time);
$month = date('n',$curr_time);
$day = date('j',$curr_time);
$today = date($fmt, $curr_time);
$r = array (
'all' => $sep.$sep.$sep,
'today' => $today.$sep.$today,
'yesterday' => date($fmt, strtotime('-1 day',$curr_time)).
$sep.date($fmt, strtotime('-1 day',$curr_time)),
'last7days' => date($fmt, strtotime('-7 day',$curr_time)).$sep.
$today,
'thismonth' => date($fmt, mktime(0,0,0,$month, 1, $year)).$sep.
$today,
'thisyear' => date($fmt, mktime(0,0,0,1, 1, $year) ).$sep.
$today,
);
return $r;
}
?>
neemias dot godinho at yahoo dot com dot br 01-Dec-2010 07:41
this function returns the current date of server subtracted from a number of
days passed as parameter
<?php
function subtractDaysFromToday($number_of_days)
{
$today = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
?>
vlado dot nikolchev at gmail dot com 30-Nov-2010 11:13
Simple and handy function that offsets a MySQL formatted date and returns the
new correctly formatted date
<?php
/**
*
* @param string $dt // MySQL formatted date (like 2010-01-01)
* @param int $year_offset // like 2 or -2, or 5 or -5 ...
* @param int $month_offset // like 2 or -2, or 5 or -5 ...
* @param in $day_offset // like 2 or -2, or 5 or -5 ...
* @return string // the new MySQL formatted date (like 2009-07-
01)
*/
function MySQLDateOffset($dt,$year_offset='',$month_offset='',$day_offset='')
{
return ($dt=='0000-00-00') ? '' :
date ("Y-m-d", mktime(0,0,0,substr($dt,5,2)+$month_offset,substr($dt,8,2)+
$day_offset,substr($dt,0,4)+$year_offset));
}
?>
Examples:
<?php
echo MySQLDateOffset('2010-06-01',2,5,15);
echo MySQLDateOffset('2010-06-01',-6,5,38);
<?php
// If today is the last day of the month, do stuff
if(date('j') == date('t')) {
// Do Stuff
}
?>
Gledison 09-Nov-2010 02:24
Simple function to return the last business day of a given month (but this
does not check holidays)
Função para retornar o último dia útil de um determinado mês (não verifica
feriados)
example:
<?php echo last_business_day(2010,02); //2010-02-26 ?>
<?php
function last_business_day($year,$month)
{
$lbd = cal_days_in_month(CAL_GREGORIAN, $month, $year);
$wday = date("N",strtotime("$year-$month-$lbd"));
if ($wday == 7) $lbd -= 2;
if ($wday == 6) $lbd--;
$lbd = date("Y-m-d",strtotime("$year-$month-$lbd"));
return $lbd;
}
?>
mijreed at yahoo dot com 17-Oct-2010 08:02
A function I use for 'date ago' used on message/comment boards
First, use this date('ymdHi') whenever entering the timestamp into your
database.
Here's the function to retrieve how long ago it was entered. $querydate is
timestamp retrieved from the database. Just call this function.
<?php
function returnDate($querydate){
return $date_string;
}
?>
Richard dot buskirk at buskirkgraphics dot com 13-Oct-2010 03:30
Here is a very simple function to get quarterly dates.
<?php
function quarter($month='',$day='')
{
if($month != ""){$tm = mktime(0,0,0,$month,$day-1,date('Y'));}else{$tm =
date('Y-m-d H:i:s');}
$quarter = ceil(date("m", $tm)/3);
for($i=1; $i<=4; $i++)
{
$checkd = mktime(0,0,0,date('m')-$i,date('d'),date('Y'));
if(ceil(date("m", $checkd)/3) != "$quarter")
{
$meani = date("m", $checkd);
for($a=1; $a<=31; $a++)
{
$forman = mktime(0,0,0,$meani,$a,date('Y'));
if(ceil(date("m", $forman)/3) == "$quarter")
{
$first_day = date('d', $forman);
break;
}
}
break;
}
}
$current_quarter_dayone = date('Y-m-d H:i:s', mktime(0,0,0,$meani,
$first_day,date('Y')));
return $current_quarter_dayone;
}
?>
To find the start of a particular quarter based on a date, pass the month and
day.
$quarter_start = quarter('08','30');
$quarter_end = date("Y-m-d H:i:s", strtotime($barter)-86400);
Results
**********************************
2010-06-01 00:00:00
2010-08-31 00:00:00
imran at t555 dot net 04-Oct-2010 02:02
Here is a simple function that gets all the dates between 2 given dates and
returns an array (including the dates specified):
<?php
// Usage
$dates_array = dates_inbetween('2001-12-28', '2002-01-01');
?>
jlathrop at horizonit dot us 25-Sep-2010 10:42
Looking to output number of days left in the current year (and check if its a
leap year - here it is)
<?php
$today = getdate(); // Get the current day in an array
$yday = ($today['yday']); // Extract just the number of days since
January 1st current year
$leap = date('L'); // check if its a leap year
$tdl = $leap + 365; // 365 days in an average year plus 1 day if
its a leap year
$dliy = $tdl - $yday; //Today number of days in the current year
minus number of days since January 1st current year
// Build the output using the above variables
echo "As of today " . date('l F d, Y, ') . "We currently have " . $dliy . "
days left in the year.";
?>
root dot packet at gmail dot com 25-Sep-2010 03:49
If you are sick of writing lots of code to format dates correctly, then I hope
you find my code useful. It can def. use some work, I plan to improve it, but
it passed a boring night and gave good results. enjoy! God bless!
<?php
function datefmt($date, $inFormat, $outFormat) {
/* A function to take a date in ($date) in specified inbound format (eg
mm/dd/yy for 12/08/10) and
* return date in $outFormat (eg yyyymmdd for 20101208)
* datefmt (
* string $date - String containing the literal
date that will be modified
* string $inFormat - String containing the format
$date is in (eg. mm-dd-yyyy)
* string $outFormat - String containing the
desired date output, format the same as date()
* )
*
*
* ToDo:
* - Add some error checking and the sort?
*/
$order = array('mon' => NULL, 'day' => NULL, 'year' => NULL);
for ($i=0; $i<strlen($inFormat);$i++) {
switch ($inFormat[$i]) {
case "m":
$order['mon'] .= substr($date, $i, 1);
break;
case "d":
$order['day'] .= substr($date, $i, 1);
break;
case "y":
$order['year'] .= substr($date, $i, 1);
break;
}
}
$unixtime = mktime(0, 0, 0, $order['mon'], $order['day'], $order['year']);
$outDate = date($outFormat, $unixtime);
<?php
/**
* formats the date passed into format required by 'datetime' attribute of
<date> tag
* if no intDate supplied, uses current date.
* @param intDate integer optional
* @return string
**/
function getDateTimeValue( $intDate = null ) {
echo getDateTimeValue();
?>
Rithish 25-Aug-2010 07:31
If you want to get yesterday's date, then a single line of code is enough.
<?php
$yesterday = date("Ymd", strtotime("-1 day"));
?>
peter_silvester at yahoo dot com 20-Aug-2010 11:40
Function to return whether or not a given date falls within British Summer
Time:
<?php
function is_bst($date) {
<?php
function DateIndo($str) {
if ($str =="") {
// null
return false;
}
else {
setlocale (LC_TIME, 'id_ID');
$date = strftime( "%d-%m-%Y %H:%I:%S", strtotime($str));
return $date;
}
}
<?php
$timezone = new DateTimeZone( "Europe/London" );
$date = new DateTime();
$date->setTimezone( $timezone );
echo $date->format( 'H:i:s A / D, M jS, Y' );
?>
Irrespective of current server location, this will output the local time in
London, Europe.
No need to reset the server timezone back to the previous setting.
lb at bostontech dot net 30-Nov-2009 07:11
Not sure why this got ignored the first time, but this is an even simpler way
to check leap year:
<?php
function isLeapYear($year)
{ return ((($year%4==0) && ($year%100)) || $year%400==0) ? (true):(false);
}
?>
d basin 14-Oct-2009 10:35
convert an "excel" formatted date. Example:
<?php
$excel_date = 40179;
echo($normal_date);
?>
result: "01/01/2010"
Marcin Szychowski 08-Oct-2009 01:59
MS-DOS related filesystems, along with ZIP files, store date and time in four
bytes (time: 2 bytes, date: 2 bytes), as described in Wikipedia:
http://en.wikipedia.org/wiki/File_Allocation_Table#Directory_table
<?php
$dosTime=($hour<<11)+($min<<5)+$sec;
$m[0]=$dosTime%256;
$m[1]=(($dosTime-$m[0])/256)%256;
return sprintf('%c%c', $m[0], $m[1]);
}
$dosDate=($year<<9)+($month<<5)+$day;
$m[0]=$dosDate%256;
$m[1]=(($dosDate-$m[0])/256)%256;
return sprintf('%c%c', $m[0], $m[1]);
}
?>
For example
<?php
$t = microtime(true);
$micro = sprintf("%06d",($t - floor($t)) * 1000000);
$d = new DateTime( date('Y-m-d H:i:s.'.$micro,$t) );
print $d->format("Y-m-d H:i:s.u");
?>
critic at hot dot ee 30-Aug-2009 08:36
If u want to get weekday date -
30.08.2009 weekdays are 24-30
i want to get 5-th day of that week - 28.08.2009
<?PHP
return $loop_date;
}
}
}
?>
czerpmac [at] gmail [dot] com 29-Aug-2009 06:02
Easy way to numeric representation of a quarter from passed as parametr date.
<?php
/**
* quarterByDate()
*
* Return numeric representation of a quarter from passed free-form date.
*
* @param mixed $date
* @return integer
*/
function quarterByDate($date)
{
return (int)floor(date('m', strtotime($date)) / 3.1) + 1;
}
?>
Example:
<?php
$quarter = quarterByDate(date('Y-m-d')); // current quarter. For 2009-08-29
will be "3"
$quarter = quarterByDate('2009-12'); // will be "4"
$quarter = quarterByDate('March'); // will be "1"
?>
Best regards,
S_P_E_C
kenaniah at gmail dot com 25-Aug-2009 11:31
This function behaves like date, but allows you to output the date in a given
time zone locale.
<?php
function date_at_timezone($format, $locale, $timestamp=null){
if(is_null($timestamp)) $timestamp = time();
//Prepare to calculate the time zone offset
$current = time();
//Switch to new time zone locale
$tz = date_default_timezone_get();
date_default_timezone_set($locale);
//Calculate the offset
$offset = time() - $current;
//Get the date in the new locale
$output = date($format, $timestamp - $offset);
//Restore the previous time zone
date_default_timezone_set($tz);
return $output;
}
//Examples
$t = time();
<?php
$tz = date_default_timezone_get();
date_default_timezone_set('UTC');
for($i=0; $i<7; $i++)
echo date('D', mktime(12, 0, 0, 1, $i+4, 1970)) . '<br />';
date_default_timezone_set($tz);
?>
Change 'D' to 'l' (lowercase 'L') for full names. Change $i+4 to $i+5 if you
want Monday to be the first day of the week.
christophermmann at gmail dot com 19-Aug-2009 11:44
I couldn't find a function to do this properly. All functions I could find
would use the current month as an argument.
<?php
echo findFirstDayofWeek(6,2009, "Wednesday", 2);
?>
Where 6 is "June", 2009 is the year, Wednesday is the weekday we want and 2 is
the 2nd occurence.
<?php
<?php
function addOrdinal($num=0){
return $num.(((strlen($num)>1)&&(substr($num,-2,1)=='1'))?
'th' : date("S",mktime(0,0,0,0,substr($num,-1),0)));
} // end function addOrdinal
?>
Just.Kevin 28-Jul-2009 04:52
In order to determine if a year is a leap year an earlier poster suggested
simply checking to see if the year is a multiple of four:
<?php
function is_leapyear_broken($year = 2004) {
return ($year%4)==0;
}
?>
While this will work for the majority of years it will not work on years that
are multiples of 100 but not multiples of 400 i.e.(2100).
A function not using php's date() function that will also account for this
small anomaly in leap years:
<?php
function is_leapyear_working($year = 2004) {
if((($year%4==0) && ($year%100!=0)) || $year%400==0) {
return true;
}
return false;
}
?>
While is_leapyear_working will not return true for the few non-leap years
divisible by four I couldn't tell you if this is more or less efficient than
using php's date() as an even earlier poster suggested:
<?php
function is_leapyear($year = 2004) {
$is_leap = date('L', strtotime("$year-1-1"));
return $is_leap;
}
?>
get.mango at gmail.com (Mangesh Sangapu) 28-Jul-2009 04:31
(Referring to the leap year posts)
Not every year that is divisible by 4 is a leap year. There are other
conditions. Here's the complete list:
<?php
function is_leapyear($year) {
if ( ($year%4) != 0 )
{ return false; }
if ( ($year%100)==0 )
{
if ( ($year%400) == 0 )
{ return true; }
else
{ return false; }
}
else
{ return true; }
}
?>
seanj 24-Jul-2009 02:58
An earlier user posted a script to detect whether or not a given year is a
leap year:
<?php
function is_leapyear($year = 2004) {
$is_leap = date('L', strtotime("$year-1-1"));
return $is_leap;
}
?>
You're thinking too hard! Just check to see if the year is a multiple of four:
<?php
function is_leapyear($year = 2004) {
return ($year%4)==0;
}
?>
<?php
/*
these are the russian additional format characters
д: full textual representation of the day of the week
Д: full textual representation of the day of the week (first character is
uppercase),
к: short textual representation of the day of the week,
К: short textual representation of the day of the week (first character is
uppercase),
м: full textual representation of a month
М: full textual representation of a month (first character is uppercase),
л: short textual representation of a month
Л: short textual representation of a month (first character is uppercase),
*/
function date_ru($formatum, $timestamp=0) {
if (($timestamp <= -1) || !is_numeric($timestamp)) return '';
$q['д'] = array(-1 => 'w', 'воскресенье','понедельник', 'вторник', 'среда',
'четверг', 'пятница', 'суббота');
$q['Д'] = array(-1 => 'w', 'Воскресенье','Понедельник', 'Вторник', 'Среда',
'Четверг', 'Пятница', 'Суббота');
$q['к'] = array(-1 => 'w', 'вс','пн', 'вт', 'ср', 'чт', 'пт', 'сб');
$q['К'] = array(-1 => 'w', 'Вс','Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб');
$q['м'] = array(-1 => 'n', '', 'января', 'февраля', 'марта', 'апреля',
'мая', 'июня', 'июля', 'августа', 'сентября', 'октября', 'ноября', 'декабря');
$q['М'] = array(-1 => 'n', '', 'Января', 'Февраля', 'Март', 'Апреля', 'Май',
'Июня', 'Июля', 'Август', 'Сентября', 'Октября', 'Ноября', 'Декабря');
$q['л'] = array(-1 => 'n', '', 'янв', 'фев', 'мар', 'апр', 'май', 'июн',
'июл', 'авг', 'сен', 'окт', 'ноя', 'дек');
$q['Л'] = array(-1 => 'n', '', 'Янв', 'Фев', 'Мар', 'Апр', 'Май', 'Июн',
'Июл', 'Авг', 'Сен', 'Окт', 'Ноя', 'Дек');
if ($timestamp == 0)
$timestamp = time();
$temp = '';
$i = 0;
while ( (strpos($formatum, 'д', $i) !== FALSE) || (strpos($formatum, 'Д',
$i) !== FALSE) ||
(strpos($formatum, 'к', $i) !== FALSE) || (strpos($formatum, 'К',
$i) !== FALSE) ||
(strpos($formatum, 'м', $i) !== FALSE) || (strpos($formatum, 'М',
$i) !== FALSE) ||
(strpos($formatum, 'л', $i) !== FALSE) || (strpos($formatum, 'Л',
$i) !== FALSE)) {
$ch['д']=strpos($formatum, 'д', $i);
$ch['Д']=strpos($formatum, 'Д', $i);
$ch['к']=strpos($formatum, 'к', $i);
$ch['К']=strpos($formatum, 'К', $i);
$ch['м']=strpos($formatum, 'м', $i);
$ch['М']=strpos($formatum, 'М', $i);
$ch['л']=strpos($formatum, 'л', $i);
$ch['Л']=strpos($formatum, 'Л', $i);
foreach ($ch as $k=>$v)
if ($v === FALSE)
unset($ch[$k]);
$a = min($ch);
$temp .= date(substr($formatum, $i, $a-$i), $timestamp) .
$q[$formatum[$a]][date($q[$formatum[$a]][-1], $timestamp)];
$i = $a+1;
}
$temp .= date(substr($formatum, $i), $timestamp);
return $temp;
}
DATE_RSS will return the timezone that your server is in as part of the
format, which is normally correct when formatting a date for an RSS feed (RFC-
822).
However, if you're in the UK and it's the summer, your timezone is set as
"BST". This is not actually a valid RFC-822 timezone, thereby rendering
DATE_RSS a bit useless for six months of the year.
The valid extension would actually be GMT. You should therefore adjust the
time back by 1 hour and substitute the BST for GMT.
rez dot eza at gmail dot com 27-May-2009 04:12
<?php
//for Indonesian get return today
<?php
$answer = is_leapyear(2000);
if($answer) {
<?php
function LastWeek(){
$week = date('W');
$year = date('Y');
$lastweek=$week-1;
if ($lastweek==0){
$week = 52;
$year--;
}
$lastweek=sprintf("%02d", $lastweek);
for ($i=1;$i<=7;$i++){
$arrdays[] = strtotime("$year". "W$lastweek"."$i");
}
return $arrdays;
}
$days = LastWeek();
echo "last week between " . date('Ymd000000',$days[0]) . " and " .
date('Ymd235959', $days[6]) . "\n";
?>
eduardo at digmotor dot com dot br 21-Apr-2009 08:34
Thanks to tcasparr at gmail dot com for the great idea (at least for me) ;)
I changed the code a little to replicate the functionality of
date_parse_from_format, once I don't have PHP 5.3.0 yet. This might be useful
for someone. Hope you don't mind changing your code tcasparr at gmail dot com.
<?php
/*******************************************************
* Simple function to take in a date format and return array of associated
* formats for each date element
*
* @return array
* @param string $strFormat
*
* Example: Y/m/d g:i:s becomes
* Array
* (
* [year] => Y
* [month] => m
* [day] => d
* [hour] => g
* [minute] => i
* [second] => s
* )
*
* This function is needed for PHP < 5.3.0
********************************************************/
function dateParseFromFormat($stFormat, $stData)
{
$aDataRet = array();
$aPieces = split('[:/.\ \-]', $stFormat);
$aDatePart = split('[:/.\ \-]', $stData);
foreach($aPieces as $key=>$chPiece)
{
switch ($chPiece)
{
case 'd':
case 'j':
$aDataRet['day'] = $aDatePart[$key];
break;
case 'F':
case 'M':
case 'm':
case 'n':
$aDataRet['month'] = $aDatePart[$key];
break;
case 'o':
case 'Y':
case 'y':
$aDataRet['year'] = $aDatePart[$key];
break;
case 'g':
case 'G':
case 'h':
case 'H':
$aDataRet['hour'] = $aDatePart[$key];
break;
case 'i':
$aDataRet['minute'] = $aDatePart[$key];
break;
case 's':
$aDataRet['second'] = $aDatePart[$key];
break;
}
}
return $aDataRet;
}
?>
<?php
function changeDateFormat($stDate,$stFormatFrom,$stFormatTo)
{
// When PHP 5.3.0 becomes available to me
//$date = date_parse_from_format($stFormatFrom,$stDate);
//For now I use the function above
$date = dateParseFromFormat($stFormatFrom,$stDate);
return date($stFormatTo,mktime($date['hour'],
$date['minute'],
$date['second'],
$date['month'],
$date['day'],
$date['year']));
}
?>
Anonymous 14-Apr-2009 02:10
Heads up: The date('W') week number of the year is computed based on Monday,
and may not be exactly what you expect. What is "Week 01" of year 2008? This
is different from the date('z') day number of the year which is computed from
January 1 == day zero.
<?php // RAY_date_W.php
echo "<br/>" . date('W', strtotime("December 28, 2008")); // 52
echo "<br/>" . date('W', strtotime("December 29, 2008")); // 01
echo "<br/>" . date('W', strtotime("January 2, 2009")); // 01
if (!date('z', strtotime("January 1"))) echo "<br/>FALSE"; // FALSE
?>
tcasparr at gmail dot com 13-Apr-2009 05:21
<?php
/**
* Simple function to take in a date format and return array of associated
formats for each date element
* @return array
* @param string $strFormat
*
* Example: Y/m/d g:i:s becomes
* Array
* (
* [year] => Y
* [month] => m
* [day] => d
* [hour] => g
* [minute] => i
* [second] => s
* )
*/
function extract_date_format($strFormat)
{
$format_array = array();
$pieces = split('[:/.\ \-]', $strFormat);
foreach($pieces as $piece)
{
switch ($piece)
{
case 'd':
case 'j':
$format_array['day'] = $piece;
break;
case 'F':
case 'M':
case 'm':
case 'n':
$format_array['month'] = $piece;
break;
case 'o':
case 'Y':
case 'y':
$format_array['year'] = $piece;
break;
case 'g':
case 'G':
case 'h':
case 'H':
$format_array['hour'] = $piece;
break;
case 'i':
$format_array['minute'] = $piece;
break;
case 's':
$format_array['second'] = $piece;
break;
}
}
return $format_array;
}
?>
pierre 24-Feb-2009 10:22
It seems to me that you can reliably get the week range of a certain numeric
week like so:
<?php
Just remember you must pad the week number if it's under 10. 1 won't work, it
should be 01.
uramihsayibok, gmail, com 21-Jan-2009 02:47
In a refreshing change, this code snippet is *not* about calculating date
differences or anything like that.
<background-story>
I've always preferred date() over strftime() because of what each offers. For
example, date has an st/nd/rd for the day number (S) while strftime does not.
It also has an unpadded day number (j) that strftime doesn't (%e pads it with
a space).
On the other hand, each character in the format string for date() is
translated unless you prepend a backslash...
Recently I've wanted to create links with date information in it. Like with
"January 21st 2009" each part would be a link (January => /2009/01, 21st =>
/2009/01/21, 2009 => /2009). date() makes this difficult because the HTML
markup gets the treatment as well as the Y/m/d characters. Escaping all of
those is ugly, not to mention annoying.
</background-story>
<?php
/**
* Combines placeholders from date() with the % marker from strftime()
*
* Like strftime, use %% for a literal %.
*
* @see date, strftime
* @param string $format The format of the outputted date string
* @param int $timestamp An integer Unix timestamp that defaults to the
current local time
* @return A formatted date string
*/
function strfdate($format, $timestamp = null) {
// look for tokens
if (preg_match_all('/(?<!%)(%%)*%(.)/', $format, $matches)) {
// passing false or null as the timestamp doesn't work so we
// have to generate the default ourselves
if ($timestamp === null) $timestamp = time();
// run each token through date - all at once
// combines them into a "a!b!c!d" list, runs it through date,
// and splits it apart again
$parts = explode("!", date(implode("!", $matches[2]), $timestamp));
// (! should never show up in date() output so this works)
?>
mrkrackham 18-Nov-2008 07:33
Just in case anyone else is looking for an easy-to-find equivalent for W3C
Datetime or date("c") in a previous version of php, here's one I did. Hope it
helps someone.
<?php
function w3cDate($time=NULL)
{
if (empty($time))
$time = time();
$offset = date("O",$time);
return date("Y-m-d\TH:i:s",$time).substr($offset,0,3).":".substr($offset,-
2);
}
?>
Examples:
echo w3cDate(); //2008-11-18T12:15:18-07:00
echo w3cDate(mktime(2,3,4,5,6,2007)); //2007-05-06T02:03:04-06:00
sourabhshankar AT gmail DOT com 14-Nov-2008 08:43
<?php
/*
Find out start and end date of current week.
I am assuming that week starts at sunday and ends at saturday.
so a typical week will look like this: sun,mon,tue,wed,thu,fri,sat
if you find any bug/error, please email me.
*/
/*
OUTPUT (m-d-y):
11-09-2008
11-15-2008
*/
?>
Kenneth Kin Lum 02-Oct-2008 10:52
date(DATE_RFC822) and date(DATE_RFC2822) both work. note that RFC 822 is
obsoleted by RFC 2822. The main difference is the year being 08 in RFC 822
and is 2008 in RFC 2822.
<?php
function udate($format, $utimestamp = null)
{
if (is_null($utimestamp))
$utimestamp = microtime(true);
<?php
$sdate=date('c',strtotime(date('Y')."W".date('W')."0"));
$edate=date('c',strtotime(date('Y')."W".date('W')."7"));
?>
this stands for year - 2008, constant never changes - W, week number of the
year - 20, day of the week - 0 for sunday, 1 for monday, etc....
I spend today 3 hours to correct scripts which were created with such error by
previous programmer, so please, guys, don't make me work like this and
remember about conversation to LOCAL time.
phprocks at aol dot com 06-Aug-2008 06:25
Try this for finding the difference in days between 2 dates/datetimes... take
note though, date_parse requires PHP version 5.1.3 or higher.
<?php
/**
* Finds the difference in days between two calendar dates.
*
* @param Date $startDate
* @param Date $endDate
* @return Int
*/
function dateDiff($startDate, $endDate)
{
// Parse dates for conversion
$startArry = date_parse($startDate);
$endArry = date_parse($endDate);
<?php
/**
* Returns array of next 7 days starting with today
*
*/
function next_7_days() {
// create array of day names. You can change these to whatever you
want
$days = array(
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday',
'Sunday');
$today = date('N');
for ($i=1;$i<$today;$i++) {
It basically takes an array starting with Monday and shifts each day to the
end of the array until the first element in the array is today.
con_tobe at yahoo dot com 10-Jul-2008 03:46
Doing $w-- for months ending on Sat won't hurt (i.e. if you're counting weeks
as is the case below), but halocastle's code is perfectly fine as is and quite
fast. He/she uses $w as a key for the $weeks array. "Halo" does this BEFORE
$w++, so $w-- is superfluous as the loop has already ended. For May, 2008, I
get 5 weeks as expected...
Array
(
[1] => Array
(
[4] => 1
[5] => 2
[6] => 3
)
------------OMITTED-----------------
[4] => 22
[5] => 23
[6] => 24
)
I guess the one pit-fall of the code is if you overlap months, say the
following year, then $m-- makes perfect since...I think (haven't gotten that
far...yet).
I modified "Halo's" code to include months, too (this is from a snippet that
produces a three month calendar, hence the outer $months loop, omitted here).
<?php
$m = date('m');
$Y = date('Y');
Enjoy!
halocastle at yahoo dot com 01-Jul-2008 04:20
Weeks and days for any month/year combo:
<?php
$m = 2; // February
$Y = 2008;
print_r($week):
-----------------------
Array
(
[1] => Array
(
[5] => 1
[6] => 2
)
[2] => Array
(
[0] => 3
[1] => 4
[2] => 5
[3] => 6
[4] => 7
[5] => 8
[6] => 9
)
[EDIT BY danbrown AT php DOT net: In a note dated 03-JUL-08, (dmagick AT gmail
DOT com) offered the following amendment to this note.]
[I've updated this] code as it doesn't take into account when a month finishes
on a Saturday (eg May 2008).
<?php
$start_date = mktime(0, 0, 0,$start_month, 1, $start_year);
$days_in_month = date('t', $start_date);
$month_first_day = date('w', $start_date);
$j = $month_first_day;
$num_weeks = 1;
<?php
function chooseDate($timestamp = ""){
if($timestamp == ""){
$timestamp = time();
}
$months = array(null, 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul',
'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
unset($months[0]);
print_r($months);
$out = '<select name="month">';
foreach($months as $key => $month){
if($month == date('M', $timestamp)){
$out .= '<option value="'.$key.'" selected="selected">'.
$month.'</option>';
}else{
$out .= '<option value="'.$key.'">'.$month.'</option>';
}
}
$out .= '</select><select name="days">';
for($i = 1; $i <= 32; $i++){
if($i == date('j', $timestamp)){
$out .= '<option value="'.$i.'" selected="selected">'.
$i.'</option>';
}else{
$out .= '<option value="'.$i.'">'.$i.'</option>';
}
}
$out .= "</select><select name='year'>";
for($i = date('Y'); $i >= 1970; $i--){
if($i == date('Y', $timestamp)){
$out .= '<option value="'.$i.'" selected="selected">'.
$i.'</option>';
}else{
$out .= '<option value="'.$i.'">'.$i.'</option>';
}
}
$out .= "</select>";
return $out;
}
?>
Usage is simple:
<?php
echo chooseDate(); // Will select current date
echo chooseDate(1149566400); // Will select June 6th, 2006
?>
kontakt at arthur minus schiwon dot de 18-Jun-2008 10:29
to get the week of the month simply use:
ceil( date("j") / 7 );
diego at diego dot eng dot br 09-Jun-2008 11:27
I made a small code to get the last working day of the month:
<?php
$times = strtotime(date("Y")."-".date("m")."-".date("t"));
for ($lastworkingday=0;$lastworkingday==0;$times-=86400)
if (date("w",$times)!=0 && date("w",$times)!=6) $lastworkingday = date("j",
$times);
print $lastworkingday;
?>
phil dot taylor at enilsson dot com 26-May-2008 05:37
Found this helpful when converting unix dates for use with the ical file
format.
<?php
// Converts a unix timestamp to iCal format (UTC) - if no timezone is
// specified then it presumes the uStamp is already in UTC format.
// tzone must be in decimal such as 1hr 45mins would be 1.75, behind
// times should be represented as negative decimals 10hours behind
// would be -10
function unixToiCal($uStamp = 0, $tzone = 0.0) {
$uStampUTC = $uStamp + ($tzone * 3600);
$stamp = date("Ymd\THis\Z", $uStampUTC);
return $stamp;
}
?>
chubby at chicks dot com 23-May-2008 01:54
<?php
/**
* Checks wether a date is between an interval
*
* Usage:
*
* // check if today is older than 2008/12/31
* var_dump(currentDayIsInInterval('2008/12/31'));
* // check if today is younger than 2008/12/31
* var_dump(currentDayIsInInterval(null,'2008/12/31'));
* // check if today is between 2008/12/01 and 2008/12/31
* var_dump(currentDayIsInInterval('2008/12/01','2008/12/31'));
*
* Will trigger errors if date is in wrong format, notices if $begin >
$end
*
* @param string $begin Date string as YYYY/mm/dd
* @param string $end Date string as YYYY/mm/dd
* @return bool
*/
function currentDayIsInInterval($begin = '',$end = '')
{
$preg_exp = '"[0-9][0-9][0-9][0-9]/[0-9][0-9]/[0-9][0-9]"';
$preg_error = 'Wrong parameter passed to function '.__FUNCTION__.' :
Invalide date
format. Please use YYYY/mm/dd.';
$interval_error = 'First parameter in '.__FUNCTION__.' should be
smaller than
second.';
if(empty($begin))
{
$begin = 0;
}
else
{
if(preg_match($preg_exp,$begin))
{
$begin = (int)str_replace('/','',$begin);
}
else
{
trigger_error($preg_error,E_USER_ERROR);
}
}
if(empty($end))
{
$end = 99999999;
}
else
{
if(preg_match($preg_exp,$end))
{
$end = (int)str_replace('/','',$end);
}
else
{
trigger_error($preg_error,E_USER_ERROR);
}
}
if($end < $begin)
{
trigger_error($interval_error,E_USER_WARNING);
}
$time = time();
$now = (int)(date('Y',$time).date('m',$time).date('j',$time));
if($now > $end or $now < $begin)
{
return false;
}
return true;
}
?>
wilson dot p dot pereira at itelefonica dot com dot br 22-May-2008 03:37
The function below extracts any date time value basead in the string format.
Returns an associative array with day,month,year,hour,min and seg separated.
<?php
function ExtractDateTimeByFormat($strDateTime, $strFormat="dmYHis")
{
//extract the format
$i = 0;
$aFieldOrder = array();
$nFields = 0;
$strExtraction = "";
while(isset($strFormat[$i]))
{
$strField = $strFormat[$i];
switch ( strtolower($strField) )
{
case "D";
case "d";
$aFieldOrder[$nFields] = "d";
$nFields++;
$strExtraction .= "%d";
if(isset($strFormat[$i+1]))
{
$strExtraction .= "%*1c";
}
break;
case "M";
case "m";
$aFieldOrder[$nFields] = "m";
$nFields++;
$strExtraction .= "%d";
if(isset($strFormat[$i+1]))
{
$strExtraction .= "%*1c";
}
break;
case "y";
case "Y";
$aFieldOrder[$nFields] = "y";
$nFields++;
$strExtraction .= "%4d";
if(isset($strFormat[$i+1]))
{
$strExtraction .= "%*1c";
}
break;
case "h";
case "H";
$aFieldOrder[$nFields] = "h";
$nFields++;
$strExtraction .= "%d";
if(isset($strFormat[$i+1]))
{
$strExtraction .= "%*1c";
}
break;
case "i";
$aFieldOrder[$nFields] = "i";
$nFields++;
$strExtraction .= "%d";
if(isset($strFormat[$i+1]))
{
$strExtraction .= "%*1c";
}
break;
case "S";
case "s";
$aFieldOrder[$nFields] = "s";
$nFields++;
$strExtraction .= "%d";
if(isset($strFormat[$i+1]))
{
$strExtraction .= "%*1c";
}
break;
}
$i++;
}
}
?>
wulf dot kaiser at mpimf-heidelberg dot mpg dot de 21-May-2008 08:00
For output formatting of a SAMP based seminar announcement system, i had to
fetch the date of every friday of a given month in a given year. Here's what i
did:
<?php
if ($givenMonth != '12') {
else {
$nextGivenMonth = $givenMonth + 1;
$nextGivenYear = $givenYear;}
# Get the first weekday of the month
switch ($firstWeekDayOfMonth) {
$numOfDaysToFirstFriday = 1 + $numOfDaysToFirstFriday;
$firstFridayOfMonthDate = date("d.m.Y", mktime(0, 0, 0,
$givenMonth, $numOfDaysToFirstFriday, $givenYear));
$firstFridayOfMonthDay = date("d", mktime(0, 0, 0, $givenMonth,
$numOfDaysToFirstFriday, $givenYear));
# Get the last weekday of the month
switch ($lastWeekDayOfMonth) {
$numOfDaysToLastFriday = $lastDayOfMonth -
$numOfDaysToLastFriday;
$lastFridayOfMonthDate = date("d.m.Y", mktime(0, 0, 0,
$givenMonth, $numOfDaysToLastFriday, $givenYear));
$lastFridayOfMonthDay = date("d", mktime(0, 0, 0, $givenMonth,
$numOfDaysToLastFriday, $givenYear));
if ($divisor=='3') {
else if ($divisor=='4') {
?>
http://xwisdomhtml.com/dateclass.html
Anonymous 29-Feb-2008 09:05
## This will produce the first day of last month and the last day of last
month
## 2008-01-01 2008-01-31
<?php
echo date("Y-m-01", strtotime("-1 month", strtotime(date("Y-m-d"))))."
".date("Y-m-d", strtotime("-1 day", strtotime(date("Y-m-01")))) ?>
jc 31-Dec-2007 02:28
date("W") returns the iso8601 week number, while date("Y") returns the
_current_ year. This can lead to odd results. For example today (dec 31, 2007)
it returns 1 for the week and of course 2007 for the year. This is not wrong
in a strict sense because iso defines this week as the first of 2008 while we
still have 2007.
So, if you don't have another way to safely retrieve the year according to the
iso8061 week-date - strftime("%G") doesn't work on some systems -, you should
be careful when working with date("W").
?>
It works for years smaller than current year, but returns '01' when year was
the same or bigger as current year.
Not sure if I missed something or maybe misused this function but I couldn't
get it to work even with different date representations.
$weeks_in_year = strftime("%W",strtotime("12/31/2007"));
?>
PHP v.4.4.7
[EDIT BY danbrown AT php DOT net: In a note dated 25-JAN-09, "Juan Paredes"
offered the following information as an amendment.]
Complementing the information [in this note], if you want to calculate the
number of weeks in a given year, according to the week definition by ISO 8601,
the following should be enough:
date('W', mktime(0,0,0,12,28,$year) );
(the last week on a give year always contains 28-Dec)
bikinyboy at example dot com 12-Dec-2007 03:44
This function is like date, but it "speaks" Hungarian (or an other language)
<?php
/*
these are the hungarian additional format characters
ö: full textual representation of the day of the week
Ö: full textual representation of the day of the week (first character is
uppercase),
ő: short textual representation of the day of the week,
Ő: short textual representation of the day of the week (first character is
uppercase),
ü: full textual representation of a month
Ü: full textual representation of a month (first character is uppercase),
ű: short textual representation of a month
Ű: short textual representation of a month (first character is uppercase),
*/
function date_hu($formatum, $timestamp=0) {
if (($timestamp <= -1) || !is_numeric($timestamp)) return '';
$q['ö'] = array(-1 => 'w', 'vasárnap', 'hétfő', 'kedd', 'szerda',
'csütörtök', 'péntek', 'szombat');
$q['Ö'] = array(-1 => 'w', 'Vasárnap', 'Hétfő', 'Kedd', 'Szerda',
'Csütörtök', 'Péntek', 'Szombat');
$q['ő'] = array(-1 => 'w', 'va', 'hé', 'ke', 'sze', 'csü', 'pé', 'szo');
$q['Ő'] = array(-1 => 'w', 'Va', 'Hé', 'Ke', 'Sze', 'Csü', 'Pé', 'Szo');
$q['ü'] = array(-1 => 'n', '', 'január', 'február', 'március', 'április',
'május', 'június', 'július', 'augusztus', 'szeptember', 'október', 'november',
'december');
$q['Ü'] = array(-1 => 'n', '', 'Január', 'Február', 'Március', 'Április',
'Május', 'Június', 'Július', 'Augusztus', 'Szeptember', 'Október', 'November',
'December');
$q['ű'] = array(-1 => 'n', '', 'jan', 'febr', 'márc', 'ápr', 'máj', 'júni',
'júli', 'aug', 'szept', 'okt', 'nov', 'dec');
$q['Ű'] = array(-1 => 'n', '', 'Jan', 'Febr', 'Márc', 'Ápr', 'Máj', 'Júni',
'Júli', 'Aug', 'Szept', 'Okt', 'Nov', 'Dec');
if ($timestamp == 0)
$timestamp = time();
$temp = '';
$i = 0;
while ( (strpos($formatum, 'ö', $i) !== FALSE) || (strpos($formatum, 'Ö',
$i) !== FALSE) ||
(strpos($formatum, 'ő', $i) !== FALSE) || (strpos($formatum, 'Ő',
$i) !== FALSE) ||
(strpos($formatum, 'ü', $i) !== FALSE) || (strpos($formatum, 'Ü',
$i) !== FALSE) ||
(strpos($formatum, 'ű', $i) !== FALSE) || (strpos($formatum, 'Ű',
$i) !== FALSE)) {
$ch['ö']=strpos($formatum, 'ö', $i);
$ch['Ö']=strpos($formatum, 'Ö', $i);
$ch['ő']=strpos($formatum, 'ő', $i);
$ch['Ő']=strpos($formatum, 'Ő', $i);
$ch['ü']=strpos($formatum, 'ü', $i);
$ch['Ü']=strpos($formatum, 'Ü', $i);
$ch['ű']=strpos($formatum, 'ű', $i);
$ch['Ű']=strpos($formatum, 'Ű', $i);
foreach ($ch as $k=>$v)
if ($v === FALSE)
unset($ch[$k]);
$a = min($ch);
$temp .= date(substr($formatum, $i, $a-$i), $timestamp) .
$q[$formatum[$a]][date($q[$formatum[$a]][-1], $timestamp)];
$i = $a+1;
}
$temp .= date(substr($formatum, $i), $timestamp);
return $temp;
}
<?php
$timezone = date("O"); // get timezone
$timezone_end = substr($timezone, -2, 2); // get last two numbers
$timezone= substr($timezone, 0, -2); // get first half
echo $timezone = $timezone . ":" . $timezone_end; // add colon
?>
snobord787 at msn dot com 30-Aug-2007 04:06
I modified (erenezgu at gmail.com)'s code so you don't have to redirect but is
stored in cookies.
<?php
if(empty($_COOKIE['offset'])) {
// Javascript is our friend!
$header='
<script type="text/javascript">
document.cookie="offset=" + ( (new Date()).getTimezoneOffset()*60)*(-
1)-'.abs(date('Z')).';
</script>
';
}
// Example Usage
echo date('d/m/Y H:i:s', time()+$_COOKIE['offset'] );
?>
pierrotevrard at gmail dot com 03-Jul-2007 11:11
For people who used "z" format...
The real range of "z" key format is 0 to 365 (instead of 366) and "z"
represent the number of spent days in the year.
See this examples :
<?php
define ("\n" , NL );
print '<pre>';
print 'On second unix day: "' . date( 'z : Y-m-d' , 3600*24 ) . '"' . NL;
//show: On second unix day: "1 : 1970-01-02"
print 'On the last day of a leap year: "' . date( 'z : Y-m-d' , mktime( 23,
59, 59, 12, 31, 2000 ) ) . '"' . NL;
//show: On the last day of a leap year: "365 : 2000-12-31"
print 'On the day after the last day of a leap year: "' . date( 'z : Y-m-d' ,
mktime( 23, 59, 59, 12, 31+1, 2000 ) ) . '"' . NL;
//show: On the day after the last day of a leap year: "0 : 2001-01-01"
print '</pre>';
?>
jcwebb at dicoe dot com 19-Jun-2007 05:48
i needed the day (eg. 27th) of the last Monday of a month
<?php
$d=cal_days_in_month(CAL_GREGORIAN,$m,$y); // days in month
if (date('l',mktime(0,0,0,$m,$d,$y))=='Monday'): $finalmonday=$d;
else: $finalmonday=date('d',strtotime('last Monday',mktime(0,0,0,$m,$d,
$y))); // day(date) of last monday of month, eg 26
endif;
?>
this also works...
<?php
$finalmonday=date('d',strtotime('last Monday',mktime(0,0,0,$m,($d+1),$y)));
//the '$d+1' is to catch the last day IS a monday (eg. dec 2007)
?>
/**
* Get date in RFC3339
* For example used in XML/Atom
*
* @param integer $timestamp
* @return string date in RFC3339
* @author Boris Korobkov
* @see http://tools.ietf.org/html/rfc3339
*/
function date3339($timestamp=0) {
if (!$timestamp) {
$timestamp = time();
}
$date = date('Y-m-d\TH:i:s', $timestamp);
?>
john at hotmail dot com 12-Jun-2007 01:55
Just a small addition to dmitriy. If the present date is in daylight saving
time, and the date in the past is not, the result will not be a whole number
by dividing by 86400. It will be something like 48.958333333. This is because
the day in which it changes from normal to daylight saving time is one hour
longer than normal (90000 secs) and the opposite is true when changing back
(the day would be one hour shorter - 82800 secs).
<?php
$digest_date = "2007-01-01";
$date_diff = round( abs(strtotime(date('y-m-d'))-strtotime($digest_date)) /
86400, 0 );
?>
pburlandoA_Remove_TgmailDOTcom 20-May-2007 07:30
This is an implementation for days360 formula used in financial calc software,
this asumes year with 360 days and months with 30 days.
<?php
/* Calc days between two dates using the financial calendar
30/360 (usa) or 30E/360(european)<-default
$fecha1 and $fecha2 in format: aaaa-mm-dd
return days or -1 in case of error.
// usage:
echo days_360("2007-01-13","2007-05-20");
?>
dmitrid at dont_show dot com 10-Mar-2007 08:14
Note for wips week limits function:
I had to run it over 52 weeks of the year and it was very slow so I've
modified to improve:
<?php
function week_limits($weekNumber, $year, $pattern)
{
$pattern = ($pattern) ? $pattern : "m/d";
$stday = 7 * $weekNumber - 7;
$stDayNumber = date("w", mktime(0,0,0,1, 1+$stday, $year));
$stUtime = mktime(0,0,0,1,1+$stday-$stDayNumber, $year);
$start_time = date($pattern, $stUtime);
$end_time = date($pattern, $stUtime+6*24*60*60);
return array($start_time, $end_time);
}//week_limits()
?>
code at ashleyhunt dot co dot uk 17-Jan-2007 09:22
I wanted to shift an sql date forward by a set time period.
This is how I achived it... well handy.
<?php
function sql_date_shift($date, $shift)
{
return date("Y-m-d H:i:s" , strtotime($shift, strtotime($date)));
}
// example usage
Hope it is of use,
Ashley
28-Nov-2006 07:26
if you are sending your data to a database, you can just send time() and then
use strftime() to turn the time() string into readable time format.
check both time() and strftime() functions both offer more or less same
functionality as date(). date() can also be used with time() strings to
display time in the past.
where time() = $data['date_quoted'] and time() is the exact time date when the
string is executed. if this is done towards a database, the time() stored is
the actual server time upon script execution, no matter the time set in the
individual computer, this will record server time, unless a gmt is set in
newer versions of php (5 and up).
jack at jtr dot de 26-Nov-2006 09:30
<?php
/**
* Converts a date string from one format to another (e.g. d/m/Y => Y-m-d,
d.m.Y => Y/d/m, ...)
*
* @param string $date_format1
* @param string $date_format2
* @param string $date_str
* @return string
*/
function dates_interconv( $date_format1, $date_format2, $date_str )
{
$base_struc = split('[/.-]', $date_format1);
$date_str_parts = split('[/.-]', $date_str );
print_r( $base_struc ); echo "<br>";
print_r( $date_str_parts ); echo "<br>";
$date_elements = array();
$p_keys = array_keys( $base_struc );
foreach ( $p_keys as $p_key )
{
if ( !empty( $date_str_parts[$p_key] ))
{
$date_elements[$base_struc[$p_key]] = $date_str_parts[$p_key];
}
else
return false;
}
$dummy_ts = mktime( 0,0,0, $date_elements['m'],$date_elements['d'],
$date_elements['Y']);
return date( $date_format2, $dummy_ts );
}
$df_src = 'd/m/Y';
$df_des = 'Y-m-d';
$iso_date = dates_interconv( $df_src, $df_des, '25/12/2005');
?>
output:
2005-12-25
admin [at] xorath [dot] com 23-Oct-2006 03:13
If you want to use the date function to fix the RFC-822 format from an
allready made RSS 2.0 feed you can do it like this..
Maybe getting an external feed from another asp or php file that you cannot
change, but want to have the correct dateformat for anyway.
<?php
header('Content-type: application/rss+xml; charset=iso-8859-1');
$xmlfile = simplexml_load_file($_GET[feedURL]);
for ( $i = 0; $i < count($xmlfile->channel->item); $i++ )
$xmlfile->channel->item[$i]->pubDate = date("r",strtotime((string)
($xmlfile->channel->item[$i]->pubDate)));
echo $xmlfile->asXML();
?>
or what you want. Hope anyone can take advantage of this, I wrote it to help a
friend which had date stored in database only by yyyy-mm-dd hh:mm:ss and
retrieved via asp from another script.
Article at http://www.xorath.com/articles/?article=2
emailfire at gmail dot com 07-Oct-2006 04:39
To use the date("N") function in PHP < 5.1.0 use:
<?php
function dayofweek() {
$days = array("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun");
return array_search(date("D"), $days) + 1;
}
?>
Michiel 28-Sep-2006 03:08
If you want to count quarters between dates you can use the following:
<?php
function countQuarters($begindate, $enddate)
{
if (!isset($begindate) || empty($begindate) || !isset($enddate) ||
empty($enddate))
return -1;
$countyears = date("Y", strtotime($enddate)) - date("Y",
strtotime($begindate));
$quarters = 0;
if (date("Y", strtotime($enddate)) == date("Y",
strtotime($begindate)))
{
if (date("m", strtotime($enddate)) != date("m",
strtotime($begindate)))
{
if (date("m", strtotime($enddate)) > date("m",
strtotime($begindate)))
{
$difference = date("m", strtotime($enddate)) -
date("m", strtotime($begindate));
$quarters += ceil((int) $difference / 4);
}
else
{
return -1;
}
}
}
else
{
$quarters = (int) $countyears * 4;
if (date("m", strtotime($enddate)) != date("m",
strtotime($begindate)))
{
if (date("m", strtotime($enddate)) > date("m",
strtotime($begindate)))
{
$difference = date("m", strtotime($enddate)) -
date("m", strtotime($begindate));
$quarters += ceil((int) $difference / 4);
}
else
{
$afterbegin = 12 - (int) date("m",
strtotime($begindate));
$untilend = date("m", strtotime($enddate));
$quarters = ($quarters - 4) + ceil(($afterbegin +
$untilend) / 4);
}
}
}
return $quarters;
}
?>
russ at isitaboat dot co dot uk 06-Sep-2006 02:18
Easy way of switching between mysql and "normal" dates (english, not
american)...
<?php
function flipdate($dt, $seperator_in = '-', $seperator_out = '-')
{
return implode($seperator_out, array_reverse(explode($seperator_in, $dt)));
}
?>
michiel at mb-it dot nl 04-Sep-2006 12:59
***EDITOR NOTE: Referred to note has been removed.
<?php
function getdays($day1,$day2)
{
return round((strtotime($day2)-strtotime($day1))/(24*60*60),0);
}
So now all of you know how many days you have left to buy me a birthday
present ;)
James 29-Aug-2006 12:45
Slightly modified the code provided by "martin at smttuk dot com" so that you
can give the function a date and/or time that you choose;
<?php
function zonedate($layout, $countryzone, $daylightsaving, $time)
{
if($daylightsaving) {
$daylight_saving = date('I');
if($daylight_saving){ $zone=3600*($countryzone+1); }
}
else {
if( $countryzone>>0){ $zone=3600*$countryzone; }
else { $zone=0; }
}
if(!$time) { $time = time(); }
$date = gmdate($layout, $time + $zone);
return $date;
}
?>
For example if I wanted the time and date of my birthday in New Zealand time;
<?php
echo zonedate('Y-m-d H:i:s',-12,true,mktime(18,46,0,9,7,1986));
?>
Corey 28-Aug-2006 12:55
It's pretty simple, but in case anybody else is having problems getting the
exact time they need because of DST (ex: on a Windows box in an area without
DST), you can fix it all in a single line. Example...
<?php
echo "The time is " . date((date("I") ? intval(date("g")) - 1 : date("g"))
. ":i m/d/y") . ".";
?>
martin at smttuk dot com 25-Aug-2006 11:30
<?php
/* Country Zone : Time Zone Name
-12 : Dateline Standard
-11 : Samoa Standard Time
-10 : Hawaiian Standard Time
-8 : Pacific Standard Time
-7 : Mexican Standard Time, Mountain Standard Time
-6 : Central Standard Time, Mexico Standard Time
-5 : Eastern Standard Time Eastern Time, SA Pacific Standard Time
-4 : Atlantic Standard Time, SA Western Standard Time, Pacific SA Standard
Time
-3.5 : Newfoundland Standard Time
-3 : SA Eastern Standard Time, E. South America Standard Time
-2 : Mid:Atlantic Standard Time
-1 : Azores Standard Time, Cape Verde Standard Time
0 : Universal Coordinated Time, Greenwich Mean Time
1 : Romance Standard Time, Central Africa Standard Time, Central European
Standard Time
2 : Egypt Standard Time, South Africa Standard Time, E. Europe Standard Time,
FLE Standard Time, GTB Standard Time
3 : Arab Standard Time, E. Africa Standard Time, Arabic Standard Time, Russian
Standard Time
3.5 : Iran Standard Time
4 : Arabian Standard Time, Caucasus Standard Time, Afghanistan Standard Time
5 : West Asia Standard Time
5.5 : India Standard Time
5.75 : Nepal Standard Time
6 : Central Asia Standard Time
6.5 : Myanmar Standard Time
7 : SE Asia Standard Time, North Asia Standard Time
8 : China Standard Time, W. Australia Standard Time, Singapore Standard Time,
Taipei Standard Time, North Asia East Standard Time
9 : Tokyo Standard Time, Korea Standard Time, Yakutsk Standard Time
9.5 : AUS Central Standard Time, Cen. Australia Standard Time
10 : AUS Eastern Standard Time, E. Australia Standard Time
West Pacific Standard Time, Tasmania Standard Time, Vladivostok Standard Time
11 : Central Pacific Standard Time
12 : Fiji Standard Time, New Zealand Standard Time
13 : Tonga Standard Time
* How to use
$layout =
Same function as date : http://uk2.php.net/manual/en/function.date.php
$countryzone =
Country Zone from Above Eg: 0 ,for Greenwich Mean Time
$daylightsaving =
Set true if the Country has daylight saving it will auto change.
Set false if the Country dose not have daylight saving or wish to it
Disabled.
(About Daylight Saving go here :
http://www.timeanddate.com/time/aboutdst.html)
Call Function:
zonedate($layout, $countryzone, $daylightsaving);
E.g.
If GMT = Friday 25th of August 2006 10:23:17 AM
When Function called:
// West Asia Standard Time (Country Uses daylight saving)
echo zonedate("l dS \of F Y h:i:s A", 5, true);
//Output : Friday 25th of August 2006 03:23:17 PM
*/
<?php
$year = date("Y", $date);
$month = date("m", $date);
if( (isset($_GET['year'])) && (intval($_GET['year']) > 1582) )
{
$year = intval($_GET['year']);
}
if( (isset($_GET['month'])) && (intval($_GET['month']) >= 1) &&
(intval($_GET['month']) <= 12) )
{
$month = intval($_GET['month']);
}
$date = mktime(1, 1, 1, $month, date("d"), $year);
?>
The check for weeknumber of the end of the month being smaller than the
beginning of the month, is because of December. Where Monday 31st is actually
in the first week of the following year.
The +1 adjustment is for the number of weeks, inclusive. ie if January had
five week, then 5-1=4, so we need to add an extra one to make it 5.
Phil Sylvia 08-Aug-2006 04:05
I simplified this after I figured it out based upon Mel Boyce's simple
solution. Thanks Mel!
I wanted to calculate dates based upon any given date and not just todays
date which is what the hundreds of examples on the Internet use. I created a
simple function and then just call the function with 2 parameters.. the date
(string) to test and the number of days that I want to add (positive #) or
subtract (negative #) My intended use is to retrieve dates from the database
and perform the date calculations. This makes it simple. I hope this helps
someone as frustrated as I was. Enjoy.
******************************************
<?php
function fnc_date_calc($this_date,$num_days){
$my_time = strtotime ($this_date); //converts date string to UNIX
timestamp
$timestamp = $my_time + ($num_days * 86400); //calculates # of days passed
($num_days) * # seconds in a day (86400)
$return_date = date("Y/m/d",$timestamp); //puts the UNIX timestamp back
into string format
return $return_date;//exit function and return string
}//end of function
$date_to_test = "2006/08/11";
$days_to_add = 7;
$past_date = fnc_date_calc($date_to_test,(($days_to_add)*-1));
$future_date = fnc_date_calc($date_to_test,$days_to_add);
<?php
function getMondays($year) {
$newyear = $year;
$week = 0;
$day = 0;
$mo = 1;
$mondays = array();
$i = 1;
while ($week != 1) {
$day++;
$week = date("w", mktime(0, 0, 0, $mo,$day, $year));
}
array_push($mondays,date("r", mktime(0, 0, 0, $mo,$day, $year)));
while ($newyear == $year) {
$test = strtotime(date("r", mktime(0, 0, 0, $mo,$day, $year)) . "+" .
$i . " week");
$i++;
if ($year == date("Y",$test)) {
array_push($mondays,date("r", $test));
}
$newyear = date("Y",$test);
}
return $mondays;
}
?>
dulare at gmail dot com 13-Jul-2006 03:36
If You are looking for some simple date calculations:
<?php
function days_between($fyear, $fmonth, $fday, $tyear, $tmonth, $tday)
{
return abs((mktime ( 0, 0, 0, $fmonth, $fday, $fyear) - mktime ( 0, 0, 0,
$tmonth, $tday, $tyear))/(60*60*24));
}
?>
Elena S. 05-May-2006 09:36
If you do not PHP5 yet but want a week day to be in ISO format: 1 (for Monday)
through 7 (for Sunday), you can use this:
<?php
?>
mel dot boyce at gmail dot com 06-Apr-2006 11:46
I've been flicking through the comments looking for some succinct date code
and have noticed an alarming number of questions and over-burdened examples
related to date mathematics. One of the most useful skills you can utilize
when performing date math is taking full advantage of the UNIX timestamp. The
UNIX timestamp was built for this kind of work.
Another usage could find itself in a class submitted by Kyle M Hall which aids
in the creation of timestamps from the recent past for use with MySQL. Rather
than the looping and fine tuning of a date, Kyle can use the raw UNIX
timestamps (this is untested code):
<?php
$ago = 14; // days
$timestamp = time() - ($ago * 86400);
?>
Hopefully these two examples of "UNIX-style" timestamp usage will help those
finding date mathematics more elusive than it should be.
SpikeDaCruz 09-Mar-2006 07:12
The following function will return the date (on the Gregorian calendar) for
Orthodox Easter (Pascha). Note that incorrect results will be returned for
years less than 1601 or greater than 2399. This is because the Julian calendar
(from which the Easter date is calculated) deviates from the Gregorian by one
day for each century-year that is NOT a leap-year, i.e. the century is
divisible by 4 but not by 10. (In the old Julian reckoning, EVERY 4th year
was a leap-year.)
<?php
function getOrthodoxEaster($date){
/*
Takes any Gregorian date and returns the Gregorian
date of Orthodox Easter for that year.
*/
$year = date("Y", $date);
$r1 = $year % 19;
$r2 = $year % 4;
$r3 = $year % 7;
$ra = 19 * $r1 + 16;
$r4 = $ra % 30;
$rb = 2 * $r2 + 4 * $r3 + 6 * $r4;
$r5 = $rb % 7;
$rc = $r4 + $r5;
//Orthodox Easter for this year will fall $rc days after April 3
return strtotime("3 April $year + $rc days");
}
?>
erwinmoller at xs4all dot nl 05-Jan-2006 12:34
If you need dates that are prior to 1970 (or 1901 for php5.1), have a look at
calendar at this very site:
http://www.php.net/calendar
Nick H 24-Nov-2005 02:21
Users in GMT may find some information on British Summer Time useful.
Personally I was confused that date() for a timestamp of 0 was returning 1am,
until I found about the all-year BST from 1968-71.
http://wwp.greenwichmeantime.com/info/bst2.htm
vernon at vernonkesner dot com 02-Nov-2005 05:37
The examples for getting a date in the past or future is simply not the best
way to do it. Especially if you are doing it dynamically.
I find the best way to get a date in the past or future is like this:
<?php
//get timestamp for past/future date I want
$pf_time = strtotime("-3 days");
//format the date using the timestamp generated
$pf_date = date("Y-m-d", $pf_time);
?>
martin at kurahaupo dot gen dot nz 30-Oct-2005 09:52
There is a mistaken impression that the maximum difference between UTC and
localtime is +/- 12 hours. Right now it is summer here in New Zealand, and
we're 13 hours ahead of UTC, and further east in the Chatham Islands it's
UTC+13:45.
Consequently, the range for the "Z" conversion is at least -43200 ... +49500
mbirth at webwriters dot de 25-Oct-2005 10:24
Using 'B' for the Swatch Internet Time (i.Beats) can still lead to
misunderstandings, because the date given in the resulting string is the local
date, not the date of the BMT (Biel Mean Time / UTC+0100) after which the
i.Beats are counted. So while @000 is equal all around the globe, October 25th
2005 @000 in Chicago is really October 24th, 06:00 PM local time.
Otherwise, if you use date('d M Y @B') in Chicago on that day at 6pm, it will
return "24 Oct 2005 @000" although it should be "25 Oct 2005 @000".
So it may happen that you miss an appointment by 24 hours (or 1000 Beats ;-)
<?php
$curtime = time();
$utcdiff = date('Z', $curtime); // get difference to UTC in seconds
$bmttime = $curtime - $utcdiff + 3600; // BMT = UTC+0100
$ssm = date('H', $bmttime)*3600 + date('i', $bmttime)*60 + date('s',
$bmttime); // seconds since midnight (BMT)
$ibeats = $ssm/86.4; // 86400 seconds = 1000 beats, so 1 beat = 86.4
seconds
Note: If you would try date('D, d M Y @B', $bmttime), the resulting beats
would be wrong because the timezone used for calculation of the beats within
the date() function is still your local one but the timestamp is UTC+0100.
Another working way would be:
<?php
$curtime = time();
$utcdiff = date('Z', $curtime); // get difference to UTC in seconds
$bmttime = $curtime - $utcdiff + 3600; // BMT = UTC+0100
But this way there are no floating-point beats possible, which may be handy
sometimes.
kbrill at multi dot com 15-Sep-2005 03:27
I created a routine that fills an array with the dates in the current week.
For example $WeekDays[0] is sunday's date, $WeekDays[1] is monday's date and
so on no matter what day of the week it is today.
<?php
$lowEnd=date("w");
$lowEnd=-$lowEnd;
$highEnd=$lowEnd + 6;
$weekday=0;
for ($i=$lowEnd; $i<=$highEnd; $i++) {
$WeekDate[$weekday]=date("m/d",mktime(0, 0, 0, date("m") ,
date("d")+$i, date("Y")));
$weekday++;
}
?>
webmaster [AT] gn-solutions [DOT] de 07-Sep-2005 11:19
For users who want a different language than english, you can user strftime()
function in combination with setlocale() instead of date():
Greetings, Andy!
jon AT standardise DOT us 15-Feb-2005 04:57
Don't forget that months start on the 1st day, and not a zero date. Might
seem obvious but:
Since there is date("W") many still seem to have a problem regarding how many
weeks there are in an year. Some rather complex solutions have been shown
here.
It's defined, that a week which begins in december and ends in january the
following year belongs to the year where most of its days lie. Therefore a
week with at least 4 days in december is the last week of that year and a week
with at least 4 days in january is the first week in the new year.
This concludes, that the last week of a year always contains the 28th day of
december. So if you take date("W") on that day of a given year you always get
the correct number of weeks for that year.
The other end of that definition is that the 4th day of january always lies in
the first week of a year.
(For those asking what all this fuzz about counting weeks is about: normally
theres 52 weeks in a year but sometimes its 53 weeks in a year)
<?php
function weeks($year) {
return date("W",mktime(0,0,0,12,28,$year));
}
?>
php at document-root dot de 14-Apr-2004 05:02
To convert an unix timestamp to suite the syntax of a GeneralizedTime
attribute for OpenLDAP, you can use
date ('YmdHiZO'). Note that this conversion uses local time, the recommended
way is to store dates in UTC.
<?php
function getOrthodoxEaster($date){
/*
Takes any Gregorian date and returns the Gregorian
date of Orthodox Easter for that year.
*/
$year = date("Y", $date);
$r1 = $year % 19;
$r2 = $year % 4;
$r3 = $year % 7;
$ra = 19 * $r1 + 16;
$r4 = $ra % 30;
$rb = 2 * $r2 + 4 * $r3 + 6 * $r4;
$r5 = $rb % 7;
$rc = $r4 + $r5;
//Orthodox Easter for this year will fall $rc days after April 3
return strtotime("3 April $year + $rc days");
}
?>
add a note
show source | credits | stats | sitemap | contact | advertising | mirror sites
Copyright © 2001-2011 The PHP Group
All rights reserved.
This mirror generously provided by: Yahoo! Inc.
Last updated: Tue Jan 18 17:22:01 2011 UTC