|
 |
date (PHP 3, PHP 4, PHP 5) date -- Форматирует системную дату/время Описаниеstring date ( string format [, int timestamp] )
Возвращает время, отформатированное в соответствии с аргументом
format, используя метку времени, заданную
аргументом timestamp или текущее системное
время, если timestamp не задан.
Другими словами, timestamp является
необязательным и по умолчанию равен значению, возвращаемому функцией
time().
Замечание:
Для большинства систем допустимыми являются даты с 13 декабря
1901, 20:45:54 GMT по 19 января 2038, 03:14:07 GMT. (Эти даты
соответствуют минимальному и максимальному значению 32-битового
целого со знаком). Для Windows допустимы даты с 01-01-1970 по 19-01-2038.
Замечание:
Для получения метки времени из строкового представления даты можно
использовать функцию strtotime(). Кроме того,
некоторые базы данных имеют собственные функции для преобразования
внутреннего представления даты в метку времени (напрмер, функция
MySQL UNIX_TIMESTAMP).
Таблица 1. В параметре format распознаются
следующие символы
Символ в строке format | Описание | Пример возвращаемого значения |
---|
a | Ante meridiem или Post meridiem в нижнем регистре | am или pm | A | Ante meridiem или Post meridiem в верхнем регистре | AM или PM | B | Время в стадарте Swatch Internet | От 000 до 999 | c | Дата в формате ISO 8601 (добавлено в PHP 5) | 2004-02-12T15:19:21+00:00 | d | День месяца, 2 цифры с ведущими нулями | от 01 до 31 | D | Сокращенное наименование дня недели, 3 символа | от Mon до Sun | F | Полное наименование месяца, например January или March | от January до December | g | Часы в 12-часовом формате без ведущих нулей | От 1 до 12 | G | Часы в 24-часовом формате без ведущих нулей | От 0 до 23 | h | Часы в 12-часовом формате с ведущими нулями | От 01 до 12 | H | Часы в 24-часовом формате с ведущими нулями | От 00 до 23 | i | Минуты с ведущими нулями | 00 to 59 | I (заглавная i) | Признак летнего времени | 1, если дата соответствует летнему времени, иначе 0 otherwise. | j | День месяца без ведущих нулей | От 1 до 31 | l (строчная 'L') | Полное наименование дня недели | От Sunday до Saturday | L | Признак високосного года | 1, если год високосный, иначе 0. | m | Порядковый номер месяца с ведущими нулями | От 01 до 12 | M | Сокращенное наименование месяца, 3 символа | От Jan до Dec | n | Порядковый номер месяца без ведущих нулей | От 1 до 12 | O | Разница с временем по Гринвичу в часах | Например: +0200 | r | Дата в формате RFC 2822 | Например: Thu, 21 Dec 2000 16:01:07 +0200 | s | Секунды с ведущими нулями | От 00 до 59 | S | Английский суффикс порядкового числительного дня месяца, 2 символа |
st, nd, rd или
th. Применяется совместно с j
| t | Количество дней в месяце | От 28 до 31 | T | Временная зона на сервере | Примеры: EST, MDT ... | U | Количество секунд, прошедших с начала Эпохи Unix (The Unix
Epoch, 1 января 1970, 00:00:00 GMT) | См. также time() | w | Порядковый номер дня недели | От 0 (воскресенье) до 6 (суббота) | W | Порядковый номер недели года по ISO-8601, первый день недели - понедельник (добавлено в PHP 4.1.0) | Например: 42 (42-я неделя года) | Y | Порядковый номер года, 4 цифры | Примеры: 1999, 2003 | y | Номер года, 2 цифры | Примеры: 99, 03 | z | Порядковый номер дня в году (нумерация с 0) | От 0 до 365 | Z | Смещение временной зоны в секундах. Для временных зон
западнее UTC это отрицательное число, восточнее UTC - положительное. | От -43200 до 43200 |
Любые другие символы, встреченные в строке format,
будут выведены в результирующую строку без изменений.
Z всегда возвращает 0 при
использовании gmdate().
Пример 1. Примеры использования функции date()
<?php
echo date("l");
echo date("l dS of F Y h:i:s A");
echo "July 1, 2000 is on a " . date("l", mktime(0, 0, 0, 7, 1, 2000));
?>
|
|
Избежать распознавания символа как форматирующего можно, если экранировать
этот символ с помощью \ Если в сочетании с
\ символ являееся специальным (например,
\t), следует добавлять еще один
\.
Пример 2. Экранирование символов в функции date()
<?php
echo date("l \\t\h\e jS");
?>
|
|
Функции date() и
mktime() для вывода прошедших и будущих дат.
Пример 3.
date() и mktime()
example
<?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);
?>
|
|
Замечание:
Этот метод более надежен, чем вычитание и прибавление секунд
к метке времени, так как mktime()
учитывает любые неоднозначности в датах (переход на летнее/зимнее время
и др.).
Приведем еще несколько примеров использования функции
date(). Помните, что следует экранировать все
символы, которые вы хотите видеть в результате работы функции без
изменений. Это относится и к символам, которые в текущей версии PHP
не распознаются как специальные, так как этим символам может быть
назначено значение в следующих версиях.
Используйте одинарные кавычки для предотвращения преобразования
\n в перевод строки.
Пример 4.
Форматирование с использованием date()
<?php
$today = date("F j, Y, g:i a"); $today = date("m.d.y"); $today = date("j, n, Y"); $today = date("Ymd"); $today = date('h-i-s, j-m-y, it is w Day z '); $today = date('\i\t \i\s \t\h\e jS \d\a\y.'); $today = date("D M j G:i:s T Y"); $today = date('H:m:s \m \i\s\ \m\o\n\t\h'); $today = date("H:i:s"); ?>
|
|
Для форматирования дат на других языках используйте функции
setlocale() и strftime().
См. также описание функций getlastmod(), gmdate(),
mktime(), strftime()
и time().
date
dulare at gmail dot com
13-Jul-2006 08:36
If You are looking for some simple date calculations:
<?
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) {
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));
}
?>
Aristia
08-Jul-2006 11:12
I wrote a small function for calculating birthdays. The days count doesn't seem accurate but the years and months are correct. It seems to be rough around the edges but it works for me :)
function elapsed($year, $month, $day) {
$bdaystamp = mktime(0,0,0, $month, $day, $year);
$today = date("U");
$elapsed = $today - $bdaystamp;
$years_remainder = $elapsed%31536000;
$rawyears = $elapsed-$years_remainder;
$years = $rawyears/31536000;
$months_remainder=$years_remainder%2628000;
$rawmonths = $years_remainder-$months_remainder;
$months = $rawmonths/2628000;
$days_remainder=$months_remainder%86400;
$rawdays = $months_remainder-$days_remainder;
$days = $rawdays/86400;
$yearword = "Years";
$monthword = "Months";
$daysword = "Days";
$age= $years.' '.$yearword.' '.$months.' '.$monthword.' '.$days.' '.$daysword.'';
return $age;
}
$age=elapsed("1978", "01", "18");
piranha-php_manual at thoughtcrime dot us
07-Jul-2006 01:10
hsinche,
Your code is incorrect. You add 86400 * 7 in at least one place to find the point in time exactly one week in the future. In the following circumstances, the difference between one Friday and the same time of day on the following Friday is not 86400 * 7 seconds:
* A daylight savings switch has occurred. One additional hour (3600 seconds) has been added or lost, offsetting the time of your following Friday by that amount.
* A leap year correction has been executed--e.g. on December 31st 2005, there were 86401 seconds. The clock continued onto 23:59:60 before reaching 00:00:00.
This may not mean much in your code, but it spells all kinds of trouble if you ever want to compare the result of a similar calculation with a known value, or your time-of-day falls either on or just before midnight, or any other time when the accuracy of the time-of-day matters in your application.
Although the discrete timescale (n seconds) is linear and infinite and intuitive; it does not map to the calendar and time-of-day systems, which have a laundry list of special rules, added up over time, all to varying ends.
This is why you want to use your system's calendar functions for almost all time manipulation, unless you understand the consequences and they simply don't apply, or unless you're willing to implement the chaotic and arbitrary semantic nuances of the calendar and time-of-day system yourself.
hsinche +at+ yahoo +dot+ com
05-Jul-2006 11:29
<?php
function getFriday($hour = 9, $minute = 45) {
$day = 60 * 60 * 24; switch(date("l")) {
case "Friday":
$h = date("G");
switch(TRUE) {
case $h < $hour:
case ($h == $hour && date("i") < $minute):
$nextDate = date("F j, Y");
break;
default:
$t = time() + (7 * $day);
$nextDate = date("F j, Y", $t);
}
break;
default:
$mod = 5 - date("w");
if($mod < 0) {
$mod = 6;
}
$t = time() + ($mod * $day);
$nextDate = date("F j, Y", $t);
}
echo $nextDate;
}
?>
tam at zenology dot co dot uk
17-May-2006 06:02
/* Here's a simple function which takes a UNIX timestamp and returns a fuzzy date string such as 'Yesterday 10:24', 'Wednesday 23:11', 'April 12' or 'June 2003'. It's only set up to handle dates in the past but it's easy to see how to extend it to do future dates too. */
function fuzzyDate($timestamp)
{
if($timestamp > time())
//we don't handle future dates
return date('Y-m-d H:i', $timestamp);
elseif($timestamp > mktime(0,0,0))
//since midnight so it's today
return 'Today '.date('H:i', $timestamp);
elseif($timestamp > mktime(0,0,0) - 86400)
//since midnight 1 day ago so it's yesterday
return 'Yesterday '.date('H:i', $timestamp);
elseif($timestamp > mktime(0,0,0) - 86400*7)
//since midnight 7 days ago so it's this week
return date('l H:i', $timestamp);
elseif($timestamp > mktime(0,0,0,1,1))
//since 1st Jan so it's this year
return date('F j', $timestamp);
else
//ages ago!
return date('F Y', $timestamp);
}
Elena S.
05-May-2006 02: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:
<?
$x = date( "w" );
$corrected_week_day = 7 - ( (7-$x) % (7+$x) );
?>
mel dot boyce at gmail dot com
06-Apr-2006 04: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; $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 11: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.
<?
function getOrthodoxEaster($date){
$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;
return strtotime("3 April $year + $rc days");
}
?>
rob at robmacdonald dot com
05-Feb-2006 02:24
This function takes a YEARWEEK value (most commonly returned from mysql) and examines it to get the start date and end date for the given YEARWEEK. May be of use to someone...
function findWeekPeriod($yearweek){
$aPeriod = array();
$year = substr($yearweek,0,4);
$week = substr($yearweek,4,2);
$startDay = Mon;
$endDay = Sun;
$startdate = strtotime('+' . $week . ' week',mktime(0,0,0,1,1,$year));
$enddate = $startdate;
while(date("D",$startdate) != $startDay){
$startdate = mktime(0,0,0,date("m",$startdate),date("d",$startdate)-1, date("Y",$startdate));
}
while(date("D",$enddate) != $endDay){
$enddate = mktime(0,0,0,date("m",$enddate),date("d",$enddate)+1, date("Y",$enddate));
}
return array('start' => date('l d/m/y', $startdate),
'end' => date('l d/m/y', $enddate));
return $aPeriod;
}
erwinmoller at xs4all dot nl
05-Jan-2006 04:34
If you need dates that are prior to 1970 (or 1901 for php5.1), have a look at calendar at this very site:
calendar
martin dot m at hid dot gr
19-Dec-2005 08:25
"It worked ok, except I noticed it had some trouble if you were spanning months, (i.e. 03-29-2005 to 04-10-2005)"
this is the (Daylight Saving Time ) problem. you can check if the start date and the end date are
whether or not in daylights savings time by using
date('I',$your_date) and to add or decrease with one hour.
itsacon at itsacon dot net
16-Nov-2005 02:28
Caveat when using the 'W' and 'w' options together:
The 'W' option uses the ISO-8601 standard (week ends on sunday), whereas the 'w' option has the week _start_ on sunday (sunday == 0).
vernon at vernonkesner dot com
02-Nov-2005 09: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
$pf_time = strtotime("-3 days");
$pf_date = date("Y-m-d", $pf_time);
?>
martin at kurahaupo dot gen dot nz
30-Oct-2005 01: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 03: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); $bmttime = $curtime - $utcdiff + 3600; $ssm = date('H', $bmttime)*3600 + date('i', $bmttime)*60 + date('s', $bmttime); $ibeats = $ssm/86.4; 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); $bmttime = $curtime - $utcdiff + 3600; 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.
mendoza at pvv dot ntnu dot no
13-Oct-2005 10:38
At "daykay at pdsoftware dot de":
09 != 9 so there's nothing wrong about European vs. American formats.
$ php -r 'print 09; print "\n"; print 9; print "\n";'
0
9
09 is treated as octal and since octal numbers only use the 0-7 digits, it evaluates to 0. All numbers prefixed with 0 are considered octal just as 0x are considered hexadecimal.
http://en.wikipedia.org/wiki/Computer_numbering_formats
jim at catsanddogs dot com
12-Oct-2005 03:52
To get the start date for a working week:
<?php
list($iDay, $iMonth, $iYear) = split('-', date('d-m-Y', mktime(0, 0, 0, date('n'), ((date('j')+1)-date('w')), date('Y'))));
return $iDay.'-'.$iMonth.'-'.$iYear;
?>
kbrill at multi dot com
15-Sep-2005 08: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 04: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'); ?>
With strftime() you can output it in german like this:
<?php
setlocale(LC_TIME, 'de_DE');
echo strftime('%A, %d. %B %Y'); ?>
Greetings, Andy!
steve at somejunkwelike dot com
16-Aug-2005 11:01
re: Paul_liversidge...
This is a way to get the next 10 business days, by comparing the day of the week to not be saturday or sunday. change the top two variables to get various different results... if you want to get the next 10 business days, starting in two days from today, change the first variable to 2, and the second to 14. This should yield the next 10 working days.
<?php
$how_many_business_days_ahead = 0;
$how_many_business_days_to_count = 7;
for ($i=0;$i<$how_many_business_days_to_count;$i++)
{
$jump=$i+$how_many_business_days_ahead;
$evalday = mktime(strftime ("%d/%m/%Y", strtotime("+$jump days")));
$theday = strftime("%A", strtotime("+$jump days"));
if($theday != "Saturday" and $theday != "Sunday")
{
$days = $how_many_business_days_ahead+$i;
$the_days[$j] = strftime("%A, %B %d, %Y", strtotime("+$jump days"));
$j++;
}
}
$k = $how_many_business_days_ahead;
foreach($the_days as $eachday)
{
echo "$k business days from now = $eachday<br />";
$k++;
}
?>
results:
0 business days from now = Tuesday, August 16, 2005
1 business days from now = Wednesday, August 17, 2005
2 business days from now = Thursday, August 18, 2005
3 business days from now = Friday, August 19, 2005
4 business days from now = Monday, August 22, 2005
Rob Muhlestein
05-Aug-2005 10:48
All functions that have anything to do with the internal 32-bit constrained time() system call will have this same limitation. Hopefully we'll be 64 bit by long before then, although this already creating problems with UNIX internals.
ove at junne dot dk
02-Aug-2005 11:39
I seems to me that we're rapidly apporaching another Y2K event. The date-function only handles dates up to 2038, and this is only some 30 years away. Even today is it impossible to use date() to represent my children's 50 years birthday.
Just think about it, when you're designing your code.
[ed.: This limitation is gone in PHP 5.1 and higher, although PHP itself limits integers still to 32bit]
stuff at rushsoft dot de
30-Jun-2005 02:13
ISO 8601:2000 defines:
[...] day of the year is represented by three decimal digits. The first day of any year is represented by [001] and
subsequent days are numbered in ascending sequence [...]
So don't forget increasing the return value of date("z") by one to be ISO conform, if you use this, for instance, on presentation level.
witcho at gmail dot com
07-Jun-2005 09:22
When using 'z' it should be used as how many days have passed since the beginning of the year; not as the day of the year.
"January 1" is the day 1 of the year not the day 0.
Better to add 1 when using 'z' if you really want to know the day of the year.
justin at drunkatgt dot com
04-Jun-2005 08:24
In response to pmcdevitt(at)cesales.com:
If you just want to find out what last month was, try
$lastmonth=mktime(0,0,0,date("m")-1,1,date("Y"));
$lastmonth= date("M", $lastmonth);
There is no reason to use the day of the month to determine the revious month. And every month has a 1st. You could even through an arbitrary year in there to save a fraction of a calculation.
MG_Peter at o2 dot pl
30-Apr-2005 05:05
easy way - to convert a "datetime" form mySQL into php date format....
first - get the array form mySQL, then use
<?php
date("d M Y H:i:s", strtotime($your_row['lastlogin_date']))
?>
strtotime - easy converts a datetime timestamp into time ( time() or date("U")).
llewellyntd at gmail dot com
29-Apr-2005 05:50
Here is a very easy way to get the difference, in days, between two dates:
$days = (strtotime("2005-12-31") - strtotime(date("Y-m-d"))) / (60 * 60 * 24);
print $days;
rcrodgers622 at gmail dot com
25-Mar-2005 10:08
Regarding dolso at elastech dot it's note, it's actually easier to use the 't' item to get the last day of any given month.
echo 'February ' . date('t',mktime(0,0,0,2,1,2004)) . ' is the last day of February 2004';
//Displays "The February 29 is the last day of February 2004"
The actual day of the month specified in mktime() is irrelevant, but it's best and safest to use a day that won't alter the results such as the first of the month.
jon AT standardise DOT us
15-Feb-2005 08:57
Don't forget that months start on the 1st day, and not a zero date. Might seem obvious but:
$test = date("F Y", mktime(0, 0, 0, 12, 0, 2005));
Will return November 2005, not December.
$test = date("F Y", mktime(0, 0, 0, 12, 1, 2005));
The 1st is needed to get the right month.
ag nodot nospam at netside dot de
28-Jan-2005 07: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.
function weeks($year) {
return date("W",mktime(0,0,0,12,28,$year));
}
php at document-root dot de
14-Apr-2004 10: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).
daniel
17-Feb-2004 02: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.
<?
function getOrthodoxEaster($date){
$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;
return strtotime("3 April $year + $rc days");
}
?>
| |