If you need to get the current quarter, you can simply use:
$quarter = ceil(date("n")/3);
regards,
date
(PHP 4, PHP 5)
date — ローカルの日付/時刻を書式化する
説明
指定された引数 timestamp を、与えられた フォーマット文字列によりフォーマットし、日付文字列を返します。 タイムスタンプが与えられない場合は、現在の時刻が使われます。 つまり timestamp はオプションであり そのデフォルト値は time() の値です。
パラメータ
- format
-
出力される日付文字列の書式。以下のオプションを参照ください。
以下の文字が format パラメータ文字列として認識されます format 文字 説明 戻り値の例 日 --- --- d 日。二桁の数字(先頭にゼロがつく場合も) 01 から 31 D 曜日。3文字のテキスト形式。 Mon から Sun j 日。先頭にゼロをつけない。 1 から 31 l (lowercase 'L') 曜日。フルスペル形式。 Sunday から Saturday N ISO-8601 形式の、曜日の数値表現 (PHP 5.1.0 で追加)。 1(月曜日)から 7(日曜日) S 英語形式の序数を表すサフィックス。2 文字。 st, nd, rd または th。 jと一緒に使用する ことができる。 w 曜日。数値。 0 (日曜)から 6 (土曜) z 年間の通算日。数字。(ゼロから開始) 0 から 365 週 --- --- W ISO-8601 月曜日に始まる年単位の週番号 (PHP 4.1.0 で追加) 例: 42 (年の第 42 週目) 月 --- --- F 月。フルスペルの文字。 January から December m 月。数字。先頭にゼロをつける。 01 から 12 M 月。3 文字形式。 Jan から Dec n 月。数字。先頭にゼロをつけない。 1 から 12 t 指定した月の日数。 28 から 31 年 --- --- L 閏年であるかどうか。 1なら閏年。0なら閏年ではない。 o ISO-8601 形式の年。これは Y ほぼ同じだが、ISO 週番号 (W)が前年あるいは翌年に属する場合がある点で 異なる(PHP 5.1.0 で追加)。 例: 1999 あるいは 2003 Y 年。4 桁の数字。 例: 1999または2003 y 年。2 桁の数字。 例: 99 または 03 時 --- --- a 午前または午後(小文字) am または pm A 午前または午後(大文字) AM または PM B Swatch インターネット時間 000 から 999 g 時。12時間単位。先頭にゼロを付けない。 1 から 12 G 時。24時間単位。先頭にゼロを付けない。 0 から 23 h 時。数字。12 時間単位。 01 から 12 H 時。数字。24 時間単位。 00 から 23 i 分。先頭にゼロをつける。 00 to 59 s 秒。先頭にゼロをつける。 00 から 59 u ミリ秒 (PHP 5.2.2 で追加)。 例: 54321 タイムゾーン --- --- e タイムゾーン識別子(PHP 5.1.0 で追加) 例: UTC, GMT, Atlantic/Azores I (capital i) サマータイム中か否か 1ならサマータイム中。 0ならそうではない。 O グリニッジ標準時 (GMT) との時差 例: +0200 P グリニッジ標準時 (GMT) との時差。時間と分をコロンで区切った形式 (PHP 5.1.3 で追加)。 例: +02:00 T タイムゾーンの略称 例: EST, MDT ... Z タイムゾーンのオフセット秒数。 UTC の西側のタイムゾーン用のオフセットは常に負です。そして、 UTC の東側のオフセットは常に正です。 -43200 から 50400 全ての日付/時刻 --- --- c ISO 8601 日付 (PHP 5 で追加されました) 2004-02-12T15:19:21+00:00 r » RFC 2822 フォーマットされた日付 例: Thu, 21 Dec 2000 16:01:07 +0200 U Unix Epoch (1970 年 1 月 1 日 0 時 0 分 0 秒) からの秒数 time() も参照 フォーマット文字列中の認識されない文字は、そのまま表示されます。 Z 形式は、 gmdate() で使用した場合、常に 0 を返します。
注意: この関数が受け付けるのは integer のタイムスタンプだけです。したがって、書式指定文字 u が有用となるのは date_create() で作成したタイムスタンプを用いて date_format() を使用した場合のみです。
- timestamp
-
オプションのパラメータ timestamp は、 integer 型の Unix タイムスタンプです。 timestamp が指定されなかった場合のデフォルト値は、 現在の時刻です。言い換えると、デフォルトは time() の返り値となります。
返り値
日付を表す文字列を返します。 timestamp に数字以外が使用された場合は FALSE が返され、E_WARNING レベルのエラーが発生します。
エラー / 例外
すべての日付/時刻関数は、 有効なタイムゾーンが設定されていない場合に E_NOTICE を発生させます。また、システム設定のタイムゾーンあるいは環境変数 TZ を使用した場合には E_STRICT を発生させます。 date_default_timezone_set() も参照ください。
変更履歴
| バージョン | 説明 |
|---|---|
| 5.1.0 | 有効なタイムスタンプの範囲は、通常 Fri, 13 Dec 1901 20:45:54 GMT から Tue, 19 Jan 2038 03:14:07 GMT までです (これらの日付は、32 ビット符号付き整数の最小および最大値に 対応します)。 しかし、PHP 5.1 より前のバージョンでは、システム環境によっては (例: Windows) この範囲が 1970 年 1 月 1 日から 2038 年 1 月 19 日 までに制限されます。 |
| 5.1.0 | タイムゾーンがおかしい場合に E_STRICT や E_NOTICE が発生するようになりました。 |
| 5.1.1 | PHP 5.1.1 以降、format パラメータで標準的な 日付/時刻フォーマットを指定する際に有用な 定数がいくつか追加されました。 |
例
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
// 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);
?>
注意: サマータイムがあるため、日付や月の秒数を単純にタイムスタンプに 可減算するよりもより信頼性があります。
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
?>
他の言語で日付をフォーマットするためには、date() のかわりに setlocale() および strftime() 関数を使用する必要があります。
注意
注意: 日付の文字列表現からタイムスタンプを生成するには、 strtotime() が使用できるでしょう。 さらに、いくつかのデータベースは(MySQL の » UNIX_TIMESTAMP 関数の ような)日付フォーマットからタイムスタンプへの変換関数を有しています。
PHP 5.1 以降、$_SERVER['REQUEST_TIME'] によってリクエスト開始時のタイムスタンプが取得できるようになりました。
date
03-Mar-2008 02:18
01-Mar-2008 11:17
This small snippet of code will calculate date after five business days. This will exclude Sunday, Saturday and the holidays list that’s given in array.
Date for example: 1st March 2008
<?php
$holidayList = array("04-03-2008","07-03-2008");
$j = $i = 1;
while($i <= 5)
{
$day = strftime("%A",strtotime("+$j day"));
$tmp = strftime("%d-%m-%Y",strtotime("+$j day"));
if($day != "Sunday" and $day != "Saturday" and !in_array($tmp, $holidayList))
{
$i = $i + 1;
$j = $j + 1;
}
else
$j = $j + 1;
}
$j = $j -1;
echo strftime("%A, %d-%m-%Y",strtotime("+$j day"));
?>
Result: Tuesday, 11-03-2008
01-Mar-2008 06: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")))) ?>
22-Feb-2008 07:06
The PHP4 replacement for ISO8601 posted by fokeyjoe has a little flaw:
The time in ISO is in 24 hour format, so an uppercase H must be used.
Correct format is:
$sISO8601=date('Y-m-d\TH:i:s',$nTimestamp). substr_replace(date('O',$nTimestamp),':',3,0);
Short version for NOW:
$sISO8601=date('Y-m-d\TH:i:s'). substr_replace(date('O'),':',3,0);
14-Feb-2008 06:24
get the numbers of days between two dates
function nbdays_between($jour , $mois , $an , $jour1 , $mois1 , $an1)
{
$timestamp = mktime(0, 0, 0, $mois, $jour, $an);
$timestamp2 = mktime(0, 0, 0, $mois1, $jour1, $an1);
$diff = floor(($timestamp - $timestamp2) / (3600 * 24));
return $diff;
}
09-Feb-2008 12:39
More elegant way to find week's end and begin for any date.
$day = isset($_GET['day'])? $_GET['day']: date("d",time());
$month = isset($_GET['month'])? $_GET['month']: date("m",time());
$year = isset($_GET['year'])? $_GET['year']: date("Y",time());
$w = date('w',mktime(0,0,0,$month,$day,$year));//Week day
$start_date = mktime(0, 0, 0, $month, $day-$w+1, $year); //Timestamp of Start
$end_date = mktime(0, 0, 0, $month, $day-$w+8 , $year); //Timestamp of End
26-Jan-2008 04:59
Complementing the information by ZZigc on 28-Dec-2007 07:38, 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)
14-Jan-2008 06:13
Here's an improved version of marius' and june's getWorkingDays function.
Basically, it adds floating point precision to the operation allowing you to express the difference any interval you'd like using the day as a conversion base. For example, if you want the difference in hours (which is what I needed), just multiply getWorkingDaysDifference * 24
<?php
// Gets the floating point difference in working days between two dates.
function getWorkingDays($startDate, $endDate, $holidays){
// Calculate weekday number. Monday is 1, Sunday is 7
$firstWeekdayNumber = date("N", strtotime($startDate));
$lastWeekdayNumber = date("N", strtotime($endDate));
// Normalize the dates if they're weekends or holidays as they count for full days (24 hours)
if ($firstWeekdayNumber == 6 || $firstWeekdayNumber == 7 || in_array( date("Y-m-d", strtotime($startDate)), $holidays ))
$startDate = date("Y-m-d 00:00:00", strtotime($startDate));
if ($lastWeekdayNumber == 6 || $lastWeekdayNumber == 7 || in_array( date("Y-m-d", strtotime($endDate)), $holidays ))
$endDate = date("Y-m-d 00:00:00", strtotime("+1 days", strtotime( $endDate )));
// Compute the floating-point differences in the dates
$daysDifference = (strtotime($endDate) - strtotime($startDate)) / 86400;
$fullWeeksDifference = floor($daysDifference / 7);
$remainingDaysDifference = fmod($daysDifference, 7);
// Subtract the weekends; In the first case the whole interval is within a week, in the second case the interval falls in two weeks.
if ($firstWeekdayNumber <= $lastWeekdayNumber){
if ($firstWeekdayNumber <= 6 && 6 <= $lastWeekdayNumber && $remainingDaysDifference >= 1) $remainingDaysDifference--;
if ($firstWeekdayNumber <= 7 && 7 <= $lastWeekdayNumber && $remainingDaysDifference >= 1) $remainingDaysDifference--;
}
else{
if ($firstWeekdayNumber <= 6 && $remainingDaysDifference >= 1) $remainingDaysDifference--;
// In the case when the interval falls in two weeks, there will be a Sunday for sure
$remainingDaysDifference--;
}
// Compute the working days based on full weeks +
$workingDays = $fullWeeksDifference * 5;
if ($remainingDaysDifference > 0 )
$workingDays += $remainingDaysDifference;
// Subtract the holidays
foreach($holidays as $holiday)
{
$holidayTimeStamp=strtotime($holiday);
// If the holiday doesn't fall in weekend
if (strtotime($startDate) <= $holidayTimeStamp && $holidayTimeStamp <= strtotime($endDate) && date("N",$holidayTimeStamp) != 6 && date("N",$holidayTimeStamp) != 7 && $workingDays >= 1)
$workingDays--;
}
// End of calculation, return the result now
return $workingDays;
}
?>
12-Jan-2008 10:09
<?php
/**************************************************************
* TITLE : Countdown to any particular date or event *
* Credits : Louai Munajim *
* Notes : Original script has been modified to *
produce difference *
* in seconds, it's more effective as well! *
***************************************************************/
//Any of following input can be retrieved by GET OR POST.
//Input is set for New Year event.
$year = '2008';
$month= '12';
$day = '31';
$hour = '00';
$minute = '00';
$second = '00';
//Countdown Function
function countdown($year, $month, $day, $hour, $minute, $second)
{
global $return;
global $countdown_date;
$countdown_date = mktime($hour, $minute, $second, $month, $day, $year);
$today = time();
$diff = $countdown_date - $today;
if ($diff < 0)$diff = 0;
$dl = floor($diff/60/60/24);
$hl = floor(($diff - $dl*60*60*24)/60/60);
$ml = floor(($diff - $dl*60*60*24 - $hl*60*60)/60);
$sl = floor(($diff - $dl*60*60*24 - $hl*60*60 - $ml*60));
// OUTPUT
echo "Today's date ".date("F j, Y, g:i:s A")."<br/>";
echo "Countdown date ".date("F j, Y, g:i:s A",$countdown_date)."<br/>";
echo "\n<br>";
$return = array($dl, $hl, $ml, $sl);
return $return;
}
countdown($year, $month, $day, $hour, $minute, $second);
list($dl,$hl,$ml,$sl) = $return;
echo "Countdown ".$dl." days ".$hl." hours ".$ml." minutes ".$sl." seconds left"."\n<br>";
/*
Above snippet produces following output:
Today's date January 12, 2008, XX:XX:XX PM
Countdown date December 31, 2008, 12:00:00 AM
Countdown 353 days XX hours XX minutes XX seconds left
*/
?>
06-Jan-2008 06:33
This function calculaties the days between two data (Ymd)
By example, if $datum1 = 20071215 and $datum2 = 20081215, the output will be 366 ;-)
<?php
function calculate_day_between($datum1,$datum2)
{
if( is_numeric($datum1) && is_numeric($datum2) && strlen($datum1) == 8 && strlen($datum2) == 8 )
{
$dat = ($datum1 < $datum2)? $datum1 : $datum2;
$datv = ($datum1 < $datum2)? $datum2 : $datum1;
$i = 0;
while( $dat < $datv)
{
$i++;
switch(substr($dat,6,2))
{
case '28': $dat += (substr($dat,4,2) == 02 && substr($dat,0,4)%4 > 0 )? 73 : 1;
break;
case '29': $dat += (substr($dat,4,2) == 02 && substr($dat,0,4)%4 == 0 )? 72 : 1;
break;
case '30': $dat += (in_array( substr($dat,4,2), array(04,06,09,11)))? 71 : 1;
break;
case '31': $dat += (substr($dat,4,2) == 12 )? 8870 : 70;
break;
default: $dat++;
break;
}
}
return $i-1;
}
else
{
return false;
}
}
?>
05-Jan-2008 07:49
Much easier calc to get week limits of the current week:
$lastmonday = date('U')-(date('w')+6)%7*86400;
$nextsunday = date('U')-(date('w')-7)*86400;
HTH
31-Dec-2007 11: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.
29-Dec-2007 03: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
19-Dec-2007 11:54
re: marius at svr dot ro
to anyone using marius' function, it needs some minor fixes (look for a ---->)
<?php
//The function returns the no. of business days between two dates and it skeeps the holidays
function getWorkingDays($startDate,$endDate,$holidays){
//The total number of days between the two dates. We compute the no. of seconds and divide it to 60*60*24
//We add one to inlude both dates in the interval.
$days = (strtotime($endDate) - strtotime($startDate)) / 86400 + 1;
$no_full_weeks = floor($days / 7);
$no_remaining_days = fmod($days, 7);
//It will return 1 if it's Monday,.. ,7 for Sunday
$the_first_day_of_week = date("N",strtotime($startDate));
$the_last_day_of_week = date("N",strtotime($endDate));
//---->The two can be equal in leap years when february has 29 days, the equal sign is added here
//In the first case the whole interval is within a week, in the second case the interval falls in two weeks.
if ($the_first_day_of_week <= $the_last_day_of_week){
if ($the_first_day_of_week <= 6 && 6 <= $the_last_day_of_week) $no_remaining_days--;
if ($the_first_day_of_week <= 7 && 7 <= $the_last_day_of_week) $no_remaining_days--;
}
else{
if ($the_first_day_of_week <= 6) $no_remaining_days--;
//In the case when the interval falls in two weeks, there will be a Sunday for sure
$no_remaining_days--;
}
//The no. of business days is: (number of weeks between the two dates) * (5 working days) + the remainder
//---->february in none leap years gave a remainder of 0 but still calculated weekends between first and last day, this is one way to fix it
$workingDays = $no_full_weeks * 5;
if ($no_remaining_days > 0 )
{
$workingDays += $no_remaining_days;
}
//We subtract the holidays
foreach($holidays as $holiday){
$time_stamp=strtotime($holiday);
//If the holiday doesn't fall in weekend
if (strtotime($startDate) <= $time_stamp && $time_stamp <= strtotime($endDate) && date("N",$time_stamp) != 6 && date("N",$time_stamp) != 7)
$workingDays--;
}
return $workingDays;
}
//Example:
$holidays=array("2006-12-25","2006-12-26","2007-01-01");
echo getWorkingDays("2006-12-22","2007-01-06",$holidays)
// => will return 8
?>
Otherwise, I found this very useful, thanks marius:)
14-Dec-2007 09:56
For JasonLFunk
I did some testing on the occurrence for a given date within the month (i.e 1st Monday, 2nd Wednesday, 3rd Friday, etc.).
where $dDate is a getdate() array
intval(($dDate['mday']-1)/7)+1
Returns an integer representing the week for a given date. I tested on a complete calendar month and it seems to work well.
I then convert to a string and compare to a string list of values to see if it is in the list. If it is - it qualifies. So, my list of values might be '2,4' representing every 2nd and 4th occurrence.
12-Dec-2007 12: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 10: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-Oct-2007 11:30
Hello, these notes have been very helpful and help me solve the following problem.
I have a db with scheduled items that contain a start date, a day to occur on and how many weeks from the next closest day to happen again. I wrote the following script to do the following
1. Accept : starting date, the current date, the number of weeks between occurances and the day of the week it is to occur on.
2. Find the closest future day of the week argument from the start date.
3. Find out when the next time the item should happen via the weeks inbetween and the closest day of the week to the start date.
The result could be compared with your current date to trigger your periodical item or simply to find out when the next occurances will happen.
// $startDate:Date
// $todayDate:Date
// $weeks:Int - number of weeks in between
// $wantDay:String - full day of the week
function getWeekPeriodDate($startDate,$todayDate,$weeks,$wantDay){
$startDate = date("Y-m-d", strtotime("next $wantDay" ,strtotime($startDate)));
$dayDiff = round((strtotime($startDate)-strtotime($todayDate))/(24*60*60),0);
$weekPeriodDiff = abs(round($dayDiff/7/$weeks)*$weeks);
return date("Y-m-d",strtotime($startDate . " + " . $weekPeriodDiff . " weeks"));
}
Usage :getWeekPeriodDate("2006-July-1","2007-Nov-5",8,"Tuesday")
returns : 2007-11-20 (which is the next Tuesday based on 8 week periods since the next Tuesday closest to the start date)
30-Aug-2007 01: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'] );
?>
11-Aug-2007 04:39
If there is an easier way to find the week of the month, let me know. Here is how I figured out how to do it;
date("W") - date("W",strtotime(date("F") . " 1st " . date("Y"))) + 1;
21-Jul-2007 03:00
In relation to soreenpk at yahoo dot com's message:
That code doesn't work for two dates with a difference larger than a year, for example:
$digest_date = "2006-04-14";
$date2="2007-04-15";
$date_diff = date("d",strtotime($date2)) - date("d",strtotime($digest_date));//$date_diff = 1
16-Jul-2007 11: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 08: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 02: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
15-Jun-2007 12: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 10: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 );
?>
12-Jun-2007 12:55
soreenpk - the code snippet you posted will not find the day difference between two days that are not in the same month. This will:
<?php
$digest_date = "2007-06-01";
$date_diff = abs(strtotime(date('y-m-d'))-strtotime($digest_date)) / 86400;
?>
86400 is the number of seconds in a day, so finding the date difference in seconds and converting to days will give true day difference between dates. Cheers.
21-May-2007 04: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");
?>
04-May-2007 01:52
Another method for getting close to ISO8601 using PHP4 (should cover all versions). This format gets you compliant RDF/RSS feed dates:
$sISO8601=date('Y-m-d\Th:i:s',$nTimestamp). substr_replace(date('O',$nTimestamp),':',3,0);
The main limitation I'm aware of is the non-compliant year around new year.
25-Apr-2007 04:37
To everyone who is posting functions to parse date strings and turn them into time stamps - please look at the strtotime() function. It probably already does whatever you're writing a function to do.
To the person right below me: while your function might be an extremely small bit more efficient, strtotime() will work just fine.
11-Mar-2007 05: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:
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()
06-Feb-2007 03:54
Re: steve at somejunkwelike dot com
I think this is a better function to find the business days between two dates. This function requires PHP 5.1.0.
<?php
//The function returns the no. of business days between two dates and it skeeps the holidays
function getWorkingDays($startDate,$endDate,$holidays){
//The total number of days between the two dates. We compute the no. of seconds and divide it to 60*60*24
//We add one to inlude both dates in the interval.
$days = (strtotime($endDate) - strtotime($startDate)) / 86400 + 1;
$no_full_weeks = floor($days / 7);
$no_remaining_days = fmod($days, 7);
//It will return 1 if it's Monday,.. ,7 for Sunday
$the_first_day_of_week = date("N",strtotime($startDate));
$the_last_day_of_week = date("N",strtotime($endDate));
//The two can't be equal because the $no_remaining_days (the interval between $the_first_day_of_week and $the_last_day_of_week) is at most 6
//In the first case the whole interval is within a week, in the second case the interval falls in two weeks.
if ($the_first_day_of_week < $the_last_day_of_week){
if ($the_first_day_of_week <= 6 && 6 <= $the_last_day_of_week) $no_remaining_days--;
if ($the_first_day_of_week <= 7 && 7 <= $the_last_day_of_week) $no_remaining_days--;
}
else{
if ($the_first_day_of_week <= 6) $no_remaining_days--;
//In the case when the interval falls in two weeks, there will be a Sunday for sure
$no_remaining_days--;
}
//The no. of business days is: (number of weeks between the two dates) * (5 working days) + the remainder
$workingDays = $no_full_weeks * 5 + $no_remaining_days;
//We subtract the holidays
foreach($holidays as $holiday){
$time_stamp=strtotime($holiday);
//If the holiday doesn't fall in weekend
if (strtotime($startDate) <= $time_stamp && $time_stamp <= strtotime($endDate) && date("N",$time_stamp) != 6 && date("N",$time_stamp) != 7)
$workingDays--;
}
return $workingDays;
}
//Example:
$holidays=array("2006-12-25","2006-12-26","2007-01-01");
echo getWorkingDays("2006-12-22","2007-01-06",$holidays)
// => will return 8
?>
31-Jan-2007 12:37
Determine what is next month:
I Had the same issue as matt_wbdi at hotmail dot com
Simple solution is use 1 for the day instead of date("d"), it didnt seem to matter if I use "m", or "n" for the month.
// eg:
// if today is 2007-01-30 the following:
$datePlusoneMonth = mktime(0, 0, 0, date("m")+ 1, date("d"), date("Y"));
echo date("Y-m", $datePlusoneMonth);
//returns 2007-03 which is not next month
// this worked for me:
$datePlusoneMonth = mktime(0, 0, 0, date("m")+ 1, 1, date("Y"));
echo date("Y-m", $datePlusoneMonth);
// returns 2007-02, which IS next month
30-Jan-2007 06:06
The below code doesn't work. The $next_month variable, for instance, right now, will be March, even though today is January 30th. The reason is because one month from Jan. 30th is March. But that's not the next month. I would suggest using an array of Month names instead, with their respective number as the key.
18-Jan-2007 06:22
I wanted to shift an sql date forward by a set time period.
This is how I achived it... well handy.
<?
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
23-Dec-2006 04:22
In example 3, <?php date("m") ?> is passed to mktime() for the month argument. I believe <?php date("n") ?> should be used instead so that the leading 0's don't make PHP think the arguments are octal values. The same goes for <?php date("j") ?> instead off <?php date("d") ?>.
<?php
echo mktime(0, 0, 0, 09, 09, 2006);
echo "\n";
echo mktime(0, 0, 0, 9, 9, 2006);
?>
1133326800
1157774400
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 06:30
/**
* 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
17-Nov-2006 01:56
date("W") will not take into account US-system of weeks (it starts on Sunday).
Example:
According to ISO 8601, 1 Jan 2006 is on Sunday therefore in US-system 1 -- 7 January will be 52 week and not 1st!
But date() will print 1 and not 52.
07-Nov-2006 10:06
So I wanted a little function to output an easy to read but inaccurate date. I came up with the following (probably very inefficient) little function;
<?php
function ezDate($d) {
$ts = time() - strtotime(str_replace("-","/",$d));
if($ts>31536000) $val = round($ts/31536000,0).' year';
else if($ts>2419200) $val = round($ts/2419200,0).' month';
else if($ts>604800) $val = round($ts/604800,0).' week';
else if($ts>86400) $val = round($ts/86400,0).' day';
else if($ts>3600) $val = round($ts/3600,0).' hour';
else if($ts>60) $val = round($ts/60,0).' minute';
else $val = $ts.' second';
if($val>1) $val .= 's';
return $val;
}
?>
Then I use it as follows;
<?php
echo ucwords(ezDate('2006-09-07 18:42:00')).' Ago';
?>
Which would output;
2 Months Ago
I add an acronym tag around the output also, so my users can mouse-over for the exact date.
Hope it helps someone!
26-Oct-2006 05:38
my quick and dirty code to find the season of the current date
<?php
function season() {
$limits=array('/12/21'=>'Winter', '/09/21'=>'Autumn', '/06/21'=>'Summer', '/03/21'=>'Spring', '/01/01'=>'Winter');
foreach ($limits AS $key => $value) {
$limit=date("Y").$key;
if (strtotime($adate)>=strtotime($limit)) {
return $value;
}
}
}
echo season();
?>
PS: the 21th is a good approach but not the real day.
24-Oct-2006 12: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 01: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;
}
?>
29-Sep-2006 12:08
If you want to count quarters between dates you can use the following:
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;
}
15-Sep-2006 11:15
If you have a date in the english format"Thu Sep 07 23:59:35 CEST 2006" (some times generated from logs or other systems) and you need to translate it in mm/dd/yyyy you can use the following function!
//$data="Thu Sep 07 23:59:35 CEST 2006";
function formadatedb($data)
{
$dt=explode(" ", $data);
$year=array ("Jan"=>1, "Feb"=>2, "Mar"=>3, "Apr"=>4, "May"=>5, "Jun"=>6, "Jul"=>7, "Aug"=>8, "Sep"=>9,"Oct"=>10,"Nov"=>11,"Dec"=>12);
return $year[$dt[1]]."/".$dt[2]."/".$dt[5];
}
06-Sep-2006 11: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 09: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:
<?
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 09: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 09: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 08:30
/* 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;
}
10-Aug-2006 02:34
Example 3 is really very bad programming practice. Calling date() more than once and putting the results together, can cause you to have a date or time that is inconsistent, or just plain invalid, because the system clock could easily change between the calls.
Instead, call time() once up front to get the timestamp, then pass that into each call to date() like this:
<?php
$now = time();
$tomorrow = mktime(0, 0, 0, date("m", $now) , date("d", $now)+1, date("Y", $now));
$lastmonth = mktime(0, 0, 0, date("m", $now)-1, date("d", $now), date("Y", $now));
$nextyear = mktime(0, 0, 0, date("m", $now), date("d", $now), date("Y", $now)+1);
?>
By doing this, we ensure that we're using the same system clock sampling for all date/time field formatting, thereby ensuring the results are consistent.
10-Aug-2006 12: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 01: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;
?>
05-Aug-2006 12:00
In response to the getLastWeekDay() function:
***^ EDITOR NOTE: Referred to note was removed 2006-09-07.
Changing dates for any reason by adding/subtracting secret is a really bad idea. Daylight savings will totally screw up the calculations. Your best bets are the awesome strtotime features. To get last monday for example:
$var = strtotime('last monday');
Strtotime can do all sorts of funky stuff like this.
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 06: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)
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;
}
14-Jul-2006 12: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) //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 06: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:
<?
//GET WEEK DAY 0 FOR SUNDAY, 6 FOR SATURDAY
$x = date( "w" );
$corrected_week_day = 7 - ( (7-$x) % (7+$x) );
?>
06-Apr-2006 08: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 04: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){
/*
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 09: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
20-Dec-2005 01: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.
24-Nov-2005 11: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 02: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 06: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 07: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.
16-Sep-2005 12: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 08: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!
17-Aug-2005 03: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
06-Aug-2005 02: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.
03-Aug-2005 03: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]
30-Jun-2005 06: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.
08-Jun-2005 01: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.
16-Feb-2005 01: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.
29-Jan-2005 12: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));
}
15-Apr-2004 02: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 07: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){
/*
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");
}
?>