A quick note about DATE_RSS and daylight savings...
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.
date
(PHP 4, PHP 5)
date — 格式化一个本地时间/日期
说明
返回将整数 timestamp 按照给定的格式字串而产生的字符串。如果没有给出时间戳则使用本地当前时间。换句话说,timestamp 是可选的,默认值为 time()。
自 PHP 5.1.1 起有几个有用的常量可用作标准的日期/时间格式来指定 format 参数。
自 PHP 5.1 起在 $_SERVER['REQUEST_TIME'] 中保存了发起该请求时刻的时间戳。
Note: 有效的时间戳典型范围是格林威治时间 1901 年 12 月 13 日 20:45:54 到 2038 年 1 月 19 日 03:14:07。(此范围符合 32 位有符号整数的最小值和最大值)。不过在 PHP 5.1 之前此范围在某些系统(如 Windows)中限制为从 1970 年 1 月 1 日到 2038 年 1 月 19 日。
Note: 要将字符串表达的时间转换成时间戳,应该使用 strtotime()。此外一些数据库有一些函数将其时间格式转换成时间戳(例如 MySQL 的 » UNIX_TIMESTAMP 函数)。
| format 字符 | 说明 | 返回值例子 |
|---|---|---|
| 日 | --- | --- |
| d | 月份中的第几天,有前导零的 2 位数字 | 01 到 31 |
| D | 星期中的第几天,文本表示,3 个字母 | Mon 到 Sun |
| j | 月份中的第几天,没有前导零 | 1 到 31 |
| l(“L”的小写字母) | 星期几,完整的文本格式 | Sunday 到 Saturday |
| N | ISO-8601 格式数字表示的星期中的第几天(PHP 5.1.0 新加) | 1(表示星期一)到 7(表示星期天) |
| S | 每月天数后面的英文后缀,2 个字符 | st,nd,rd 或者 th。可以和 j 一起用 |
| w | 星期中的第几天,数字表示 | 0(表示星期天)到 6(表示星期六) |
| z | 年份中的第几天 | 0 到 366 |
| 星期 | --- | --- |
| W | ISO-8601 格式年份中的第几周,每周从星期一开始(PHP 4.1.0 新加的) | 例如:42(当年的第 42 周) |
| 月 | --- | --- |
| F | 月份,完整的文本格式,例如 January 或者 March | January 到 December |
| m | 数字表示的月份,有前导零 | 01 到 12 |
| M | 三个字母缩写表示的月份 | Jan 到 Dec |
| n | 数字表示的月份,没有前导零 | 1 到 12 |
| t | 给定月份所应有的天数 | 28 到 31 |
| 年 | --- | --- |
| L | 是否为闰年 | 如果是闰年为 1,否则为 0 |
| o | ISO-8601 格式年份数字。这和 Y 的值相同,只除了如果 ISO 的星期数(W)属于前一年或下一年,则用那一年。(PHP 5.1.0 新加) | Examples: 1999 or 2003 |
| Y | 4 位数字完整表示的年份 | 例如:1999 或 2003 |
| y | 2 位数字表示的年份 | 例如:99 或 03 |
| 时间 | --- | --- |
| a | 小写的上午和下午值 | am 或 pm |
| A | 大写的上午和下午值 | AM 或 PM |
| B | Swatch Internet 标准时 | 000 到 999 |
| g | 小时,12 小时格式,没有前导零 | 1 到 12 |
| G | 小时,24 小时格式,没有前导零 | 0 到 23 |
| h | 小时,12 小时格式,有前导零 | 01 到 12 |
| H | 小时,24 小时格式,有前导零 | 00 到 23 |
| i | 有前导零的分钟数 | 00 到 59> |
| s | 秒数,有前导零 | 00 到 59> |
| 时区 | --- | --- |
| e | 时区标识(PHP 5.1.0 新加) | 例如:UTC,GMT,Atlantic/Azores |
| I | 是否为夏令时 | 如果是夏令时为 1,否则为 0 |
| O | 与格林威治时间相差的小时数 | 例如:+0200 |
| P | 与格林威治时间(GMT)的差别,小时和分钟之间有冒号分隔(PHP 5.1.3 新加) | 例如:+02:00 |
| T | 本机所在的时区 | 例如:EST,MDT(【译者注】在 Windows 下为完整文本格式,例如“Eastern Standard Time”,中文版会显示“中国标准时间”)。 |
| Z | 时差偏移量的秒数。UTC 西边的时区偏移量总是负的,UTC 东边的时区偏移量总是正的。 | -43200 到 43200 |
| 完整的日期/时间 | --- | --- |
| c | ISO 8601 格式的日期(PHP 5 新加) | 2004-02-12T15:19:21+00:00 |
| r | RFC 822 格式的日期 | 例如:Thu, 21 Dec 2000 16:01:07 +0200 |
| U | 从 Unix 纪元(January 1 1970 00:00:00 GMT)开始至今的秒数 | 参见 time() |
格式字串中不能被识别的字符将原样显示。Z 格式在使用 gmdate() 时总是返回 0。
Example#1 date() 例子
<?php
// 设定要用的默认时区。自 PHP 5.1 可用
date_default_timezone_set('UTC');
// 输出类似:Monday
echo date("l");
// 输出类似:Monday 15th of August 2005 03:12:46 PM
echo date('l dS \of F Y h:i:s A');
// 输出:July 1, 2000 is on a Saturday
echo "July 1, 2000 is on a " . date("l", mktime(0, 0, 0, 7, 1, 2000));
/* 在格式参数中使用常量 */
// 输出类似:Mon, 15 Aug 2005 15:12:46 UTC
echo date(DATE_RFC822);
// 输出类似:2000-07-01T00:00:00+00:00
echo date(DATE_ATOM, mktime(0, 0, 0, 7, 1, 2000));
?>
在格式字串中的字符前加上反斜线来转义可以避免它被按照上表解释。如果加上反斜线后的字符本身就是一个特殊序列,那还要转义反斜线。
Example#2 在 date() 中转义字符
<?php
// prints something like: Wednesday the 15th
echo date("l \\t\h\e jS");
?>
可以把 date() 和 mktime() 结合使用来得到未来或过去的日期。
Example#3 date() 和 mktime() 例子
<?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: 由于夏令时的缘故,这种方法比简单地在时间戳上加减一天或者一个月的秒数更可靠。
一些使用 date() 格式化日期的例子。注意要转义所有其它的字符,因为目前有特殊含义的字符会产生不需要的结果,而其余字符在 PHP 将来的版本中可能会被用上。当转义时,注意用单引号以避免类似 \n 的字符变成了换行符。
Example#4 date() 格式举例
<?php
// 假定今天是:March 10th, 2001, 5:16:18 pm
$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 z '); // 05-16-17, 10-03-01, 1631 1618 6 Fripm01
$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 15:16:08 MST 2001
$today = date('H:m:s \m \i\s\ \m\o\n\t\h'); // 17:03:17 m is month
$today = date("H:i:s"); // 17:16:17
?>
要格式化其它语种的日期,应该用 setlocale() 和 strftime() 函数来代替 date()。
date
11-Jun-2009 07:20
27-May-2009 12:12
<?php
//for Indonesian get return today
echo returnDate(date("N"), "day") . ", " . date("j") . " " . returnDate(date("n"), "month") . " " . date("Y");
function returnDate($num, $tipe){
$str;
switch($tipe){
case "month":
$month_name = array("", "Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember");
$str = $month_name[floor($num)];
break;
case "day":
$day_name = array("", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu", "Minggu");
$str = $day_name[floor($num)];
break;
}
return $str;
}
?>
25-May-2009 04:52
// showing how to detect a leap year
<?php
function is_leapyear($year = 2004) {
$is_leap = date('L', strtotime("$year-1-1"));
return $is_leap;
}
?>
<?php
$answer = is_leapyear(2000);
if($answer) {
echo "2000 is a leap year<BR>";
} else {
echo "2000 is not a leap year.<BR>";
}
/* Use default for the parameter */
$yy="2003";
$answer = is_leapyear(2003);
if($answer) {
echo "$yy is a leap year.<BR>";
} else {
echo "$yy is not a leap year.<BR>";
}
?>
30-Apr-2009 02:55
Function to obtain last week timestamps.
<?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";
?>
22-Apr-2009 04: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;
}
?>
Also, if you need to change the format of dates:
<?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']));
}
?>
14-Apr-2009 10: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
?>
14-Apr-2009 01: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;
}
?>
25-Feb-2009 06:22
It seems to me that you can reliably get the week range of a certain numeric week like so:
<?php
// 2009 is the year
// W01 is week number 1
// 1 is the day number (Monday), 7 would be Sunday
strtotime("2009W011");
// Example 1 (These return the days for Week 1 or 2009
Mon_timestamp = strtotime("2009W011");
Tue_timestamp = strtotime("2009W012");
Wed_timestamp = strtotime("2009W013");
Thu_timestamp = strtotime("2009W014");
Fri_timestamp = strtotime("2009W015");
Sat_timestamp = strtotime("2009W016");
Sun_timestamp = strtotime("2009W017");
// Example 2 (more dynamic)
// set the 7 dates of the week
for($i=1; $i<=7; $i++) {
$dates[$i] = strtotime($year.'W'.$week.$i);
}
?>
Just remember you must pad the week number if it's under 10. 1 won't work, it should be 01.
21-Jan-2009 10: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>
Here's my combination of date's placeholders and strftime's % markers. It's the best solution I could think of (at 5am mind you) but I'm open to suggestions.
Lots of comments because the code is rather tricky.
<?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)
// a second function is used sequentially:
// the Xth time this function is called it will replace the Xth token
// with the corresponding element in $parts (which is passed through as $a)
//
// @param array $a Meant to be $parts as defined above
// @return $a[X] where X is how many times this function has been called
$replace = create_function('$a', 'static $i = 0; return $a[$i++];');
// find each token and get the replacement data from the $replace function
// note how the text being replaced isn't used anywhere: we already know
// what it is as it was used to create the $parts array
$result = preg_replace('/(%*)%./e', '"$1" . $replace($parts)', $format);
// finally "unescape" any %s
$result = str_replace("%%", "%", $result);
return $result;
}
return $format;
}
?>
19-Nov-2008 03: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
14-Nov-2008 04: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.
*/
//sunday = start of week
$sat = 6; //saturday = end of week
$current_day=date('w');
$days_remaining_until_sat = $sat - $current_day;
$ts_start = strtotime("-$current_day days");
$ts_end = strtotime("+$days_remaining_until_sat days");
echo date('m-d-Y',$ts_start); //start date
echo '<br>';
echo date('m-d-Y',$ts_end); //end date
/*
OUTPUT (m-d-y):
11-09-2008
11-15-2008
*/
?>
03-Oct-2008 06: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.
To use date(DATE_RFC2822), a short form is date('r').
12-Sep-2008 09:01
Correct format for a MySQL DATETIME column is
<?php $mysqltime = date ("Y-m-d H:i:s", $phptime); ?>
28-Aug-2008 02:47
a date function supporting the milliseconds format character
<?php
function udate($format, $utimestamp = null)
{
if (is_null($utimestamp))
$utimestamp = microtime(true);
$timestamp = floor($utimestamp);
$milliseconds = round(($utimestamp - $timestamp) * 1000000);
return date(preg_replace('`(?<!\\\\)u`', $milliseconds, $format), $timestamp);
}
echo udate('H:i:s.u'); // 19:40:56.78128
echo udate('H:i:s.u', 654532123.04546); // 16:28:43.45460
?>
26-Aug-2008 08:32
here is the simpliest way to get the start and end date of the week;
<?php
$sdate=date('c',strtotime(date('Y')."W".date('W')."0"));
$edate=date('c',strtotime(date('Y')."W".date('W')."7"));
?>
the format is for the string in strtotime is;
2008W200
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....
so 2008W200 stands for the sunday of the 20th week of 2008.
This will only work in php 5 or better
15-Aug-2008 06:53
All novices must be very carefull when working with timestamps as second values.
From first glance it looks like date("Y-m-d H:i:s",TIMESTAMP) will return correct date, based on "how much seconds gone from 1970".
But here is the feature, it'll be corrected time, according to LOCAL timezone.
So if you take a 25200 as timestamp (10 hours),
then on one server you'll get
1970-01-01 08:00:00
and on other server you'll get
1970-01-01 09:00:00
and so on.
Though you could expect 1970-01-01 10:00:00 in all cases, because if 25200 seconds gone from 1970-01-01 00:00:00 it obviously have to be 1970-01-01 10:00:00
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.
07-Aug-2008 02: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);
// Convert dates to Julian Days
$start_date = gregoriantojd($startArry["month"], $startArry["day"], $startArry["year"]);
$end_date = gregoriantojd($endArry["month"], $endArry["day"], $endArry["year"]);
// Return difference
return round(($end_date - $start_date), 0);
}
?>
26-Jul-2008 04:22
<?php
// A demonstration of the new DateTime class for those
// trying to use dates before 1970 or after 2038.
?>
<h2>PHP 2038 date bug demo (php version <?php echo phpversion(); ?>)</h1>
<div style='float:left;margin-right:3em;'>
<h3>OLD Buggy date()</h3>
<?php
$format='F j, Y';
for ( $i = 1900; $i < 2050; $i++) {
$datep = "$i-01-01";
?>
Trying: <?php echo $datep; ?> = <?php echo date($format, strtotime($datep)); ?><br>
<?php
}
?></div>
<div style='float:left;'>
<h3>NEW DateTime Class (v 5.2+)</h3><?php
for ( $i = 1900; $i < 2050; $i++) {
$datep = "$i-01-01";
$date = new DateTime($datep);
?>
Trying: <?php echo $datep; ?> = <?php echo $date->format($format); ?><br>
<?php
}
?></div>
11-Jul-2008 12:38
Quick function for returning the names of the next 7 days of the week starting with today.
Returns an array that can be formatted to your liking.
<?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++) {
// take the first element off the array
$shift = array_shift($days);
// ... and add it to the end of the array
array_push($days,$shift);
}
// returns the sorted array
return $days;
}
?>
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.
10-Jul-2008 11: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
)
[2] => Array
(
[0] => 4
[1] => 5
------------OMITTED-----------------
[4] => 22
[5] => 23
[6] => 24
)
[5] => Array
(
[0] => 25
[1] => 26
[2] => 27
[3] => 28
[4] => 29
[5] => 30
[6] => 31
)
)
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');
// for() {months loop omitted
$var_date = mktime(0, 0, 0, $m, 1, $Y);
$month_name = date('F', $var_date);
$months[$month_name]['DAYS'] = date('t', $var_date);
$months[$month_name]['FIRST_DAY'] = date('w', $var_date);
//}
foreach($months as $month => $key) {
$weeks = array();
for($i = 1, $j = $key['FIRST_DAY'], $w = 1;$i <= $key['DAYS'];$i++) {
$weeks[$w][$j] = $i;
$j++;
if($j == 7) {
$j = 0;
$w++;
}
}
$months[$month]['WEEKS'] = $weeks;
}
?>
Enjoy!
01-Jul-2008 12:20
Weeks and days for any month/year combo:
<?php
$m = 2; // February
$Y = 2008;
// constants used here for legibility, use $vars for dynamicon...
define('MONTH_DAYS',date('t', strtotime(date($m . '/01/' . $Y))));
// w:0->6 = Sun->Sat
define('MONTH_FIRST_DAY',date('w', strtotime(date($m . '/01/' . $Y))));
for($i = 1, $j = MONTH_FIRST_DAY, $w = 1;$i <= MONTH_DAYS;$i++) {
$week[$w][$j] = $i;
$j++;
if($j == 7) {
$j = 0;
$w++;
}
}
?>
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
)
[3] => Array
(
[0] => 10
[1] => 11
[2] => 12
[3] => 13
[4] => 14
[5] => 15
[6] => 16
)
[4] => Array
(
[0] => 17
[1] => 18
[2] => 19
[3] => 20
[4] => 21
[5] => 22
[6] => 23
)
[5] => Array
(
[0] => 24
[1] => 25
[2] => 26
[3] => 27
[4] => 28
[5] => 29
)
)
[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;
for($i = 1; $i <= $days_in_month; $i++) {
$j++;
if($j == 7) {
$j = 0;
$num_weeks++;
}
}
// if the last day of the month happens to be a Saturday,
// take one off the number of weeks
// because it was being added inside the for loop.
if ($j == 0) {
$num_weeks--;
}
?>
30-Jun-2008 10:18
I wrote the following function to show a series of drop down boxes to select the date. When provided with a timestamp, that date is selected by default, when none is provided, the current date is selected.
<?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
?>
18-Jun-2008 06:29
to get the week of the month simply use:
ceil( date("j") / 7 );
10-Jun-2008 07: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;
?>
26-May-2008 01: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;
}
?>
23-May-2008 09: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;
}
?>
22-May-2008 11: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++;
}
$aValues = array();
$aValues = sscanf($strDateTime,$strExtraction);
return array_combine($aFieldOrder,$aValues);
}
?>
21-May-2008 04: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
$givenYear = $_GET["givenYear"]; # assume "2006"
$givenMonth = $_GET["givenMonth"]; # assume "12"
if ($givenMonth != '12') {
$nextGivenMonth = "1";
$nextGivenYear = $givenYear + 1;}
else {
$nextGivenMonth = $givenMonth + 1;
$nextGivenYear = $givenYear;}
# Get the first weekday of the month
$firstDayOfMonth = date("d", mktime(0, 0, 0, $givenMonth, 1, $givenYear));
$firstWeekDayOfMonth = date("l", mktime(0, 0, 0, $givenMonth, 1, $givenYear));
# Count days to first Friday
switch ($firstWeekDayOfMonth) {
case 'Monday': $numOfDaysToFirstFriday = "4"; break;
case 'Tuesday': $numOfDaysToFirstFriday = "3"; break;
case 'Wednesday': $numOfDaysToFirstFriday = "2"; break;
case 'Thursday': $numOfDaysToFirstFriday = "1"; break;
case 'Friday': $numOfDaysToFirstFriday = "0"; break;
case 'Saturday': $numOfDaysToFirstFriday = "6"; break;
case 'Sunday': $numOfDaysToFirstFriday = "5"; break;}
# Get first Friday's date
$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
$lastDayOfMonth = date("d", strtotime("-1 day", strtotime(date("$nextGivenYear-$nextGivenMonth-01"))));
$lastWeekDayOfMonth = date("l", strtotime("-1 day", strtotime(date("$nextGivenYear-$nextGivenMonth-01"))));
# Count days to last Friday
switch ($lastWeekDayOfMonth) {
case 'Monday': $numOfDaysToLastFriday = "3"; break;
case 'Tuesday': $numOfDaysToLastFriday = "4"; break;
case 'Wednesday': $numOfDaysToLastFriday = "5"; break;
case 'Thursday': $numOfDaysToLastFriday = "6"; break;
case 'Friday': $numOfDaysToLastFriday = "0"; break;
case 'Saturday': $numOfDaysToLastFriday = "1"; break;
case 'Sunday': $numOfDaysToLastFriday = "2"; break;}
# Get last Friday's date
$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));
$divisor = $lastFridayOfMonthDay - $firstFridayOfMonthDay;
$divisor = $divisor / 7;
global $divisor;
# Get the dates of all Fridays in the given Month (can be either 4 or 5)
if ($divisor=='3') {
$firstFridayOfMonth = date("Y/m/d", mktime(0, 0, 0, $givenMonth, $numOfDaysToFirstFriday, $givenYear));
$secondFridayOfMonth = date("Y/m/d", mktime(0, 0, 0, $givenMonth, $lastFridayOfMonthDay - 14, $givenYear));
$thirdFridayOfMonth = date("Y/m/d", mktime(0, 0, 0, $givenMonth, $lastFridayOfMonthDay - 7, $givenYear));
$lastFridayOfMonth = date("Y/m/d", mktime(0, 0, 0, $givenMonth, $numOfDaysToLastFriday, $givenYear));}
else if ($divisor=='4') {
$firstFridayOfMonth = date("Y/m/d", mktime(0, 0, 0, $givenMonth, $numOfDaysToFirstFriday, $givenYear));
$secondFridayOfMonth = date("Y/m/d", mktime(0, 0, 0, $givenMonth, $lastFridayOfMonthDay - 21, $givenYear));
$thirdFridayOfMonth = date("Y/m/d", mktime(0, 0, 0, $givenMonth, $lastFridayOfMonthDay - 14, $givenYear));
$fourthFridayOfMonth = date("Y/m/d", mktime(0, 0, 0, $givenMonth, $lastFridayOfMonthDay - 7, $givenYear));
$lastFridayOfMonth = date("Y/m/d", mktime(0, 0, 0, $givenMonth, $numOfDaysToLastFriday, $givenYear));}
?>
Comments, suggestions and bugfixes are welcome ;-))
26-Mar-2008 11:44
I have written a little Date Class Library for PHP that supports timestamps for dates greater than 2038 and lesser than 1970.
This library can be used in both PHP4 and PHP5.
Check it out here:
http://xwisdomhtml.com/dateclass.html
01-Mar-2008 05: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")))) ?>
31-Dec-2007 10: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").
For most cases strftime("%W") should be a safe replacement.
[edit: Much easier is to use "o" (lower case O) instead of "Y"]
29-Dec-2007 02:38
I wanted to get the number of weeks for particular year.
Example with date():
<?php
$weeks_in_year = date("W", strtotime("12/31/2007"));
?>
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.
So the workaround was using different function.
Example with strftime():
<?php
$weeks_in_year = strftime("%W",strtotime("12/31/2007"));
?>
Now it works as a charm.
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)
12-Dec-2007 11: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;
}
echo date_hu('Y. ü j. (ö) G:i');
?>
20-Nov-2007 09:24
For those of us who don't have 5.x installed (that puts a colon in the time zone)...
<?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
?>
30-Aug-2007 12: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'] );
?>
16-Jul-2007 10:18
Here is a backward compatible version of dates_interconv
http://www.php.net/manual/en/function.date.php#71397
which also works with time (hours, minutes and seconds) and months in "M" format (three letters):
<?php
/**
mod of
http://www.php.net/manual/en/function.date.php#71397
* Converts a date and time 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 "\n"; // for testing
// print_r( $date_str_parts ); echo "\n"; // for testing
$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;
}
// print_r($date_elements); // for testing
if (array_key_exists('M', $date_elements)) {
$Mtom=array(
"Jan"=>"01",
"Feb"=>"02",
"Mar"=>"03",
"Apr"=>"04",
"May"=>"05",
"Jun"=>"06",
"Jul"=>"07",
"Aug"=>"08",
"Sep"=>"09",
"Oct"=>"10",
"Nov"=>"11",
"Dec"=>"12",
);
$date_elements['m']=$Mtom[$date_elements['M']];
}
// print_r($date_elements); // for testing
$dummy_ts = mktime(
$date_elements['H'],
$date_elements['i'],
$date_elements['s'],
$date_elements['m'],
$date_elements['d'],
$date_elements['Y']
);
return date( $date_format2, $dummy_ts );
}
?>
Usage:
<?php
$df_src = 'd/m/Y H:i:s';
$df_des = 'Y-m-d H:i:s';
echo dates_interconv( $df_src, $df_des, '25/12/2005 23:59:59');
?>
Output:
2005-12-25 23:59:59
03-Jul-2007 07: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 '"z" format interpretation:' . NL . NL;
print 'On 0 timestamp: "' . date( 'z : Y-m-d' , 0 ) . '"' . NL;
//show: On 0 timestamp: "0 : 1970-01-01"
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>';
?>
20-Jun-2007 01: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)
?>
Hope it helps, BigJonMX
14-Jun-2007 11:05
<?php
/**
* 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);
$matches = array();
if (preg_match('/^([\-+])(\d{2})(\d{2})$/', date('O', $timestamp), $matches)) {
$date .= $matches[1].$matches[2].':'.$matches[3];
} else {
$date .= 'Z';
}
return $date;
}
?>
12-Jun-2007 09: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).
If you want a whole number of days use the following instead:
<?php
$digest_date = "2007-01-01";
$date_diff = round( abs(strtotime(date('y-m-d'))-strtotime($digest_date)) / 86400, 0 );
?>
21-May-2007 03:30
This is an implementation for days360 formula used in financial calc software, this asumes year with 360 days and months with 30 days.
I am looking for a reliable function to add days to a date using 30[E]/360 format.
<?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.
based on cost_analysis.py module Ver. 0.1 public domain, no license required by Harm Kirchhoff
*/
function days_360($fecha1,$fecha2,$europeo=true) {
//try switch dates: min to max
if( $fecha1 > $fecha2 ) {
$temf = $fecha1;
$fecha1 = $fecha2;
$fecha2 = $temf;
}
// get day month year...
list($yy1, $mm1, $dd1) = explode('-', $fecha1);
list($yy2, $mm2, $dd2) = explode('-', $fecha2);
if( $dd1==31) { $dd1 = 30; }
//checks according standars: 30E/360 or 30/360.
if(!$europeo) {
if( ($dd1==30) and ($dd2==31) ) {
$dd2=30;
} else {
if( $dd2==31 ) {
$dd2=30;
}
}
}
//check for invalid date
if( ($dd1<1) or ($dd2<1) or ($dd1>30) or ($dd2>31) or
($mm1<1) or ($mm2<1) or ($mm1>12) or ($mm2>12) or
($yy1>$yy2) ) {
return(-1);
}
if( ($yy1==$yy2) and ($mm1>$mm2) ) { return(-1); }
if( ($yy1==$yy2) and ($mm1==$mm2) and ($dd1>$dd2) ) { return(-1); }
//Calc
$yy = $yy2-$yy1;
$mm = $mm2-$mm1;
$dd = $dd2-$dd1;
return( ($yy*360)+($mm*30)+$dd );
}
// usage:
echo days_360("2007-01-13","2007-05-20");
?>
11-Mar-2007 04: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()
?>
18-Jan-2007 05: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
$date = "2006-12-31 21:00";
$shift "+6 hours"; // could be days, weeks... see function strtotime() for usage
echo sql_date_shift($date, $shift);
// will output: 2007-01-01 03:00:00
?>
Hope it is of use,
Ashley
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.
more or less with something like:
date("j F, Y - g:ia", $data['date_quoted'])
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).
27-Nov-2006 05: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
23-Oct-2006 11: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();
?>
Then simply link to your rss feed like this
filename.php?feedURL=http://www.example.com/rss.asp
filename.php?feedURL=http://www.example.com/rss.xml
filename.php?feedURL=http://www.example.com/rss.php
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
08-Oct-2006 12: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;
}
?>
28-Sep-2006 11: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;
}
?>
06-Sep-2006 10: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)));
}
?>
04-Sep-2006 08:59
***EDITOR NOTE: Referred to note has been removed.
The calculation function of the number of days between 2 dates by zzzdobr at gmai dot com could be done much easier:
<?php
function getdays($day1,$day2)
{
return round((strtotime($day2)-strtotime($day1))/(24*60*60),0);
}
$begin = date("Y/m/d"); // we set today as an example
$end = "2006/11/27";
getdays($begin,$end);
?>
So now all of you know how many days you have left to buy me a birthday present ;)
29-Aug-2006 08: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));
?>
28-Aug-2006 08: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") . ".";
?>
25-Aug-2006 07: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
*/
function zonedate($layout, $countryzone, $daylightsaving)
{
if ($daylightsaving){
$daylight_saving = date('I');
if ($daylight_saving){$zone=3600*($countryzone+1);}
}
else {
if ($countryzone>>0){$zone=3600*$countryzone;}
else {$zone=0;}
}
$date=gmdate($layout, time() + $zone);
return $date;
}
?>
09-Aug-2006 11:11
Number of weeks per month
I was trying to do a monthly calendar and required the number of weeks in a month, running from Monday to Sunday. Since PHP doesn't have this in its date() parameters I had to calculate it in a roundabout manner. By subtracting the week numbers away from each other we SHOULD get the number of weeks, since it is calculated on Mondays.
<?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);
$first_day_of_month = strtotime("-" . (date("d", $date)-1) . " days", $date);
$last_day_of_month = strtotime("+" . (date("t", $first_day_of_month)-1) . " days", $first_day_of_month);
$first_week_no = date("W", $first_day_of_month);
$last_week_no = date("W", $last_day_of_month);
if($last_week_no < $first_week_no) $last_week_no=date("W", strtotime("-1 week",$last_week_no)) + 1;
$weeks_of_month = $last_week_no - $first_week_no + 1;
?>
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.
09-Aug-2006 12: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
// date calculation function
// adds or subtracts a date based upon the input.
// $this_date is a string format of a valid date ie.. "2006/08/11"
// $num_days is the number of days that you would like to add (positive number) or subtract (negative number)
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);
echo "Test Date is: ".$date_to_test;
echo "<br>";
echo "Number of days to Calculate is: ".$days_to_add;
echo "<br>";
echo "Past date is: ".$past_date;
echo "<br>";
echo "Future date is: ".$future_date;
?>
For PHP 4 users wanting a format similar to ISO 8601 (http://www.w3.org/TR/NOTE-datetime):
echo date('Y-m-d H:i:s.0T');
returns something like 2006-07-27 16:54:14.0EDT
20-Jul-2006 05:48
Here's a function that takes the year as input and returns an array or dates that are mondays. (It can be used for generating weekly reports just like I did)
<?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;
}
?>
13-Jul-2006 11: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));
}
function day_before($fyear, $fmonth, $fday)
{
return date ("Y-m-d", mktime (0,0,0,$fmonth,$fday-1,$fyear));
}
function next_day($fyear, $fmonth, $fday)
{
return date ("Y-m-d", mktime (0,0,0,$fmonth,$fday+1,$fyear));
}
function weekday($fyear, $fmonth, $fday) //0 is monday
{
return (((mktime ( 0, 0, 0, $fmonth, $fday, $fyear) - mktime ( 0, 0, 0, 7, 17, 2006))/(60*60*24))+700000) % 7;
}
function prior_monday($fyear, $fmonth, $fday)
{
return date ("Y-m-d", mktime (0,0,0,$fmonth,$fday-weekday($fyear, $fmonth, $fday),$fyear));
}
?>
06-May-2006 05: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
//GET WEEK DAY 0 FOR SUNDAY, 6 FOR SATURDAY
$x = date( "w" );
$corrected_week_day = 7 - ( (7-$x) % (7+$x) );
?>
06-Apr-2006 07: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.
An example of this relates to a comment made by james at bandit-dot-co-dot-en-zed. James was looking for a way to calculate the number of days which have passed since a certain date. Rather than using mktime() and a loop, James can subtract the current timestamp from the timestamp of the date in question and divide that by the number of seconds in a day:
<?php
$days = floor((time() - strtotime("01-Jan-2006"))/86400);
print("$days days have passed.\n");
?>
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.
10-Mar-2006 03: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.)
This algorithm was first proposed by the mathematician/physicist Gauss. Its complexity derives from the fact that the calculation is based on a combination of solar and lunar calendars.
<?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");
}
?>
05-Jan-2006 08: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
24-Nov-2005 10: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
03-Nov-2005 01: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);
?>
31-Oct-2005 05: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
25-Oct-2005 06: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 ;-)
Here's a way to return the Internet Time with correct date:
<?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
echo 'i.Beats : ' . date('D, d M Y', $bmttime) . ' @' . $ibeats;
?>
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
echo 'i.Beats : ' . date('D, d M Y', $bmttime) . ' @' . date('B', $curtime);
?>
But this way there are no floating-point beats possible, which may be handy sometimes.
15-Sep-2005 11: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++;
}
?>
07-Sep-2005 07:19
For users who want a different language than english, you can user strftime() function in combination with setlocale() instead of date():
e.g. for german language:
With date you would write:
<?php
echo date('l, d. F Y'); //Output: Wednesday, 07. September 2005
?>
With strftime() you can output it in german like this:
<?php
// Set the gloabal LC_TIME constant to german
setlocale(LC_TIME, 'de_DE');
// Little bit other Syntax but better effect
echo strftime('%A, %d. %B %Y'); //Output: Mittwoch, 07. September 2005
?>
Greetings, Andy!
16-Feb-2005 12:57
Don't forget that months start on the 1st day, and not a zero date. Might seem obvious but:
<?php $test = date("F Y", mktime(0, 0, 0, 12, 0, 2005)); ?>
Will return November 2005, not December.
<?php $test = date("F Y", mktime(0, 0, 0, 12, 1, 2005)); ?>
The 1st is needed to get the right month.
28-Jan-2005 11:19
Calculus of weeks in a year.
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.
I hope this solves a lot of confusion.
(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)
I wrote it down as a function, but as this is rather trivial one might consider using the date(...) only.
<?php
function weeks($year) {
return date("W",mktime(0,0,0,12,28,$year));
}
?>
15-Apr-2004 01: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.
If your date is in UTC, just use
date ('YmdHiZ').'Z' to convert it ("Z" stands for "Zulu", which is UTC).
18-Feb-2004 06:43
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.)
This algorithm was first proposed by the mathematician/physicist Gauss. Its complexity derives from the fact that the calculation is based on a combination of solar and lunar calendars.
<?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");
}
?>
