 |
date (PHP 3, PHP 4, PHP 5) date -- 格式化一个本地时间/日期 说明string date ( string format [, int timestamp] )
返回将整数 timestamp
按照给定的格式字串而产生的字符串。如果没有给出时间戳则使用本地当前时间。换句话说,timestamp
是可选的,默认值为 time()。
提示:
自 PHP 5.1.1 起有几个有用的常量可用作标准的日期/时间格式来指定
format 参数。
提示:
自 PHP 5.1 起在 $_SERVER['REQUEST_TIME']
中保存了发起该请求时刻的时间戳。
注意:
有效的时间戳典型范围是格林威治时间 1901 年 12 月 13 日 20:45:54
到 2038 年 1 月 19 日 03:14:07。(此范围符合 32
位有符号整数的最小值和最大值)。不过在 PHP 5.1 之前此范围在某些系统(如
Windows)中限制为从 1970 年 1 月 1 日到 2038 年 1 月 19 日。
表 1. 格式字串可以识别以下 format 参数的字符串 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。
例 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)); ?>
|
|
在格式字串中的字符前加上反斜线来转义可以避免它被按照上表解释。如果加上反斜线后的字符本身就是一个特殊序列,那还要转义反斜线。
例 2. 在 date() 中转义字符
<?php // prints something like: Wednesday the 15th echo date("l \\t\h\e jS"); ?>
|
|
可以把 date() 和
mktime() 结合使用来得到未来或过去的日期。
例 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 的字符变成了换行符。
例 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()。
参见 getlastmod(),gmdate(),mktime(),strftime()
和 time()。
jasonlfunk (at) gmail dot com
10-Aug-2007 07: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;
Robert
08-Aug-2007 03:49
This will show the day (Monday, Tuesday, etc) for any given date.
<?php
$mon = 12;
$day = 31;
$year = 1980;
$stamp = mktime(0,0,0,$mon,$day,$year);
echo date('l',$stamp);
?>
me at stewartkirkpatrick dot com
29-Jul-2007 01:54
This will calculate the 'SPOT' date for FX trades (two working days hence)
<?php
// get the day
$d=date("D");
// if today is Thu or Friday add 4 days to today
if ($d=="Thu" || $d=="Fri") {
$spot = time() + (4 * 24 * 60 * 60);
echo "<p>";
echo date("d/m/Y", $spot);
echo "</p>";
}
// else just add two days to today
else {
$spot = time() + (2 * 24 * 60 * 60);
echo "<p>";
echo date("d/m/Y", $spot);
echo "</p>";
}
?>
luis dot sv at gmail dot com
20-Jul-2007 06: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
dwdaddhp at yahoo dot de
19-Jul-2007 07:55
<?php
function isago($hour, $min){
$difference=($hour*60+$min)-(date("H")*60+date("i"));
if($difference<=0)
return true;
else if($difference>0)
return false;
}
if(isago(20,0))
echo "after eight";
else
echo "befor eight";
?>
ThomasEdison
18-Jul-2007 10:16
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', 'vasrnap', 'htf', 'kedd', 'szerda', 'cstrtk', 'pntek', 'szombat');
$q[''] = array(-1 => 'w', 'Vasrnap', 'Htf', 'Kedd', 'Szerda', 'Cstrtk', 'Pntek', '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', '', 'janur', 'februr', 'mrcius', 'prilis', 'mjus', 'jnius', 'jlius', 'augusztus', 'szeptember', 'oktber', 'november', 'december');
$q[''] = array(-1 => 'n', '', 'Janur', 'Februr', 'Mrcius', 'prilis', 'Mjus', 'Jnius', 'Jlius', 'Augusztus', 'Szeptember', 'Oktber', 'November', 'December');
$q[''] = array(-1 => 'n', '', 'jan', 'febr', 'mrc', 'pr', 'mj', 'jni', 'jli', 'aug', 'szept', 'okt', 'nov', 'dec');
$q[''] = array(-1 => 'n', '', 'Jan', 'Febr', 'Mrc', 'pr', 'Mj', 'Jni', 'Jli', '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');
?>
samuel at islabinaria dot com
16-Jul-2007 02: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
Eren - erenezgu at gmail.com
13-Jul-2007 07:18
here is a simple code to print the time according to the clients timezone offset. This code gets the clients timezone with javascript and redirects the page to itself with timezone offset as a parameter.
clienttime.php :
<?php
if ( isset($_GET['clientGMT']) ){
$clientGMT=intval( $_GET['clientGMT'] );
$serverGMT=intval( date('Z') );
echo date('H:i:s',time()+$clientGMT-$serverGMT);
}
else {
?>
<SCRIPT TYPE="text/javascript">
<!--
var clientGMT=( (new Date()).getTimezoneOffset()*60)*(-1) ;//client timezone offset in seconds
document.location='clienttime.php?clientGMT='+clientGMT ;
//->
</SCRIPT>
<?php
}
?>
hunterd1972 at gmail dot com
06-Jul-2007 08:13
concatenate the values of each select statement to form the date into a month day, year format (i.e. January 1, 2007) and then use the strtotime function.
<?php
$timestamp = strtotime($month . " " . $day . ", " . $year);
?>
pierrotevrard at gmail dot com
03-Jul-2007 11:11
For people who used "z" format...
The real range of "z" key format is 0 to 365 (instead of 366) and "z" represent the number of spent days in the year.
See this examples :
<?php
define ("\n" , NL );
print '<pre>';
print '"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>';
?>
tszming at gmail dot com
03-Jul-2007 04:34
for performance wise, don't call too many date() unless you really need it
i.e.
don't:
$tomorrow = mktime(0, 0, 0, date("m") , date("d")+1, date("Y"));
but:
list($mon, $day, $year) = split("-", date("m-d-Y"));
$tomorrow = mktime(0, 0, 0, $mon , $day+1, $year);
jcwebb at dicoe dot com
19-Jun-2007 05:48
i needed the day (eg. 27th) of the last Monday of a month
<?php
$d=cal_days_in_month(CAL_GREGORIAN,$m,$y); // days in month
if (date('l',mktime(0,0,0,$m,$d,$y))=='Monday'): $finalmonday=$d;
else: $finalmonday=date('d',strtotime('last Monday',mktime(0,0,0,$m,$d,$y))); // day(date) of last monday of month, eg 26
endif;
?>
this also works...
<?php
$finalmonday=date('d',strtotime('last Monday',mktime(0,0,0,$m,($d+1),$y)));
//the '$d+1' is to catch the last day IS a monday (eg. dec 2007)
?>
Hope it helps, BigJonMX
boris at psyonline dot ru
14-Jun-2007 03: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;
}
?>
john at hotmail dot com
12-Jun-2007 01:55
Just a small addition to dmitriy. If the present date is in daylight saving time, and the date in the past is not, the result will not be a whole number by dividing by 86400. It will be something like 48.958333333. This is because the day in which it changes from normal to daylight saving time is one hour longer than normal (90000 secs) and the opposite is true when changing back (the day would be one hour shorter - 82800 secs).
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 );
?>
dmitriy dot yakovlev at gmail dot com
11-Jun-2007 03: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.
pburlandoA_Remove_TgmailDOTcom
20-May-2007 07:30
This is an implementation for days360 formula used in financial calc software, this asumes year with 360 days and months with 30 days.
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");
?>
Josue Resende
10-May-2007 03:32
...
class CalendarFunction {
function holidays($year) {
$return = array();
$return[ 1] = array(1);
$return[12] = array(25);
// feriados moveis
return $return;
}
function qtDaysPerMonth($year, $month) {
return intval(date('t', mktime(0, 0, 0, intval($month), 1, intval($year))));
}
function daysPerMonth($year) {
$return = array();
$weekday = date('w', mktime(0, 0, 0, 1, 1, intval($year)));
$holidays = CalendarFunction::holidays($year);
for ($month = 0; $month < 12; $month++) {
$qt = CalendarFunction::qtDaysPerMonth($year, $month+1);
$holidays_month = (isset($holidays[$month+1]) ? $holidays[$month+1] : array());
for($day = 1; $day <= $qt; $day++) {
if (($weekday > 0 and $weekday < 6) and !in_array($day, $holidays_month)) {
$return[$month+1][] = $day;
}
$weekday = ($weekday == 6 ? 0 : $weekday + 1);
}
}
return $return;
}
}
...
fokeyjoe at themotto dot co dot uk
03-May-2007 04: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.
bakadesu
02-May-2007 09:58
In reply to josh's suggestion, you can achieve the same thing by doing:
<?php
$date = date($syntax, strtotime($datetime));
?>
jonbarnett at gmail dot com
24-Apr-2007 07: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.
josh
23-Apr-2007 06:15
Ever had a DATETIME in a database and want to format it using the date() function? Me too. Here you go.
<?
// format MySQL DateTime (YYYY-MM-DD hh:mm:ss) using date()
function datetime($syntax,$datetime) {
$year = substr($datetime,0,4);
$month = substr($datetime,5,2);
$day = substr($datetime,8,2);
$hour = substr($datetime,11,2);
$min = substr($datetime,14,2);
$sec = substr($datetime,17,2);
return date($syntax,mktime($hour,$min,$sec,$month,$day,$year));
}
?>
soreenpk at yahoo dot com
15-Mar-2007 06:03
we can find the different in days between two date e.g now and some past date from db throught the following simple line of code;
$digest_date = "2007-03-15";
$date_diff = date("d",strtotime(date('y-m-d'))) - date("d",strtotime($digest_date));
dmitrid at dont_show dot com
10-Mar-2007 08:14
Note for wips week limits function:
I had to run it over 52 weeks of the year and it was very slow so I've modified to improve:
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()
wips at mail dot ru
15-Feb-2007 03:04
/**
* Defines week limits.
* Week numbers in [1..54]. First week is from 1st of Jan till first Sunday in year, last week is from last monday
* in year till 31st of Dec.
*
* @param int $weekNumber - Week number
* @param int $year - Year
* @return array - array($start_time, $end_time). $start_time - begin of week, $end_time - end of week in Unix timestamp.
* Precition is +-24 hours.
*/
function week_limits($weekNumber, $year)
{
// begin datetime
$time = mktime(1, 1, 1, 1, 1, $year);
// Aassuring that $weekNumber is number
$weekNumber--;
// If first week of year starts not from monday, date() will return "not correct" result (in this case first week is 0)
if (date('w', $time) == 1)
$weekNumber++;
$start_time = false;
$end_time = false;
for ($day = 1; $day <= 380; $day++)
{
if (date('W', $time) == $weekNumber && !$start_time)
$start_time = $time;
if (date('W', $time - 24*60*60) == $weekNumber && !$end_time && date('W', $time) != $weekNumber)
$end_time = $time - 24*60*60;
if ($start_time && $end_time)
break;
$time += 24*60*60;
}
return array($start_time, $end_time);
}//week_limits()
dragon at alimex dot biz
15-Feb-2007 08:30
The function posted by mybenchmarkid down is great, but I would suggest a slight change.
The "$days" line should be without the "+1" at the end:
$days = (strtotime($endDate) - strtotime($startDate)) / 86400;
and the "for" line should be with "<=" instead of "<":
for($i=0; $i<=$days; $i++)
This way you can use a specific endDate or just use today:
$days = (time() - strtotime($startDate)) / 86400;
It will work both ways.
Bobby
mybenchmarkid at yahoo dot com
13-Feb-2007 06:55
here is a function I wrote that was useful for a calendar application I was using.
It returns an array of the valid dates between two parameter dates. enjoy.
<?
function DatesBetween($startDate, $endDate){
// get the number of days between the two given dates.
$days = (strtotime($endDate) - strtotime($startDate)) / 86400 + 1;
$startMonth = date("m", strtotime($startDate));
$startDay = date("d", strtotime($startDate));
$startYear = date("Y", strtotime($startDate));
$dates;//the array of dates to be passed back
for($i=0; $i<$days; $i++){
$dates[$i] = date("n/j/Y", mktime(0, 0, 0, $startMonth , ($startDay+$i), $startYear));
}
return $dates;
}
?>
example: $dates = DatesBetween("2/27/2007","3/3/2007")
Array ( [0] => 2/27/2007 [1] => 2/28/2007 [2] => 3/1/2007 [3] => 3/2/2007 [4] => 3/3/2007 )
Eamon Straughn eamon at gizzle dot co dot uk
05-Feb-2007 09:33
Check this out this is a class i made last year for Gizzle.co.uk but sinced used on other projects and is quite a treat. It checks for a absolute valid date or datetime type. returns booleen. Disclaimer I do not take responsibility for the use of this class. I guarantees it works.
<?php
#Created By Eamon Straughn, Class extends Date() informally
class isDate
{
private $arg;
private $return = false;
private $stack;
private $stacks;
private $pos = array();
private $poss = array();
public function __construct($arg)
{
$this->arg = trim($arg);
}
private function DateType()
{
//if length is more than 10 then it is not a date
if(($n = strlen($this->arg)) > 10)
return false;
//if length is less than 6 then it is not a date
elseif($n < 6)
return false;
//get values into arrays for processing
for($i = 0; $i < $n; $i ++)
{
if(is_numeric($this->arg[$i]))
$this->stack .= (isset($this->arg[$i])) ? $this->arg[$i] : null;
elseif(($this->arg[$i] == "-") || ($this->arg[$i] == "/") || ($this->arg[$i] == "\\"))
$this->pos[$i] = (isset($i)) ? $i : null;
}
//strip values to be checked
if(is_numeric($c = substr($this->stack, 0, current($this->pos))))
$d = (strlen($c) > 2) ? substr($this->stack, current($this->pos), current($this->pos)/2) : substr($this->stack, current($this->pos), current($this->pos));
else
return false;
if(is_numeric($d))
if(is_numeric($e = substr($this->stack, end($this->pos)-1, end($this->pos)-1)));
//convert string to integer
$c = (int) $c;
$d = (int) $d;
$e = (int) $e;
//check if it is a valid date
if((checkdate($d,$c,$e)) || (checkdate($d,$e,$c)))
return true;
return false;
}
private function DateTimeType()
{
//if length is more than 10 then it is not a datetime
if(($n = strlen($this->arg)) < 10)
return false;
//if length is less than 19 then it is not a datetime
elseif($n < 19)
return false;
//get values into arrays for processing
for($i = 0; $i < $n; $i ++)
{
if(is_numeric($this->arg[$i]))
$this->stacks .= (isset($this->arg[$i])) ? $this->arg[$i] : null;
elseif(($this->arg[$i] == "-") || ($this->arg[$i] == "/") || ($this->arg[$i] == "\\") || ($this->arg[$i] == " ") || ($this->arg[$i] == ":"))
$this->poss[$i] = (isset($i)) ? $i : null;
}
//strip values to be checked
if(is_numeric($c = substr($this->stacks, 0, current($this->poss))))
$d = (strlen($c) > 2) ? substr($this->stacks, current($this->poss), current($this->poss)/2) : substr($this->stacks, current($this->poss), current($this->poss));
else
return false;
if(is_numeric($d))
$e = (strlen($c) > 2) ? substr($this->stacks, next($this->poss)-1, (next($this->poss)-1)/4) : substr($this->stacks, next($this->poss)-1, (next($this->poss)-1)/2);
if(is_numeric($e))
if(is_numeric($f = substr($this->stacks, (next($this->poss)/2)+2, 2)));
if(is_numeric($g = substr($this->stacks, (next($this->poss)/2)+2, 2)));
if(is_num
|