<pre class="brush:php;toolbar:false"><?php
/**
*功能:取得给定日期所在周的开始日期和结束日期
*参数:$gdate日期,默认为当天,格式:YYYY-MM-DD
*$first一周以星期一还是星期天开始,0为星期天,1为星期一
*返回:数组array("开始日期","结束日期");
*
*/
functionaweek($gdate="",$first=0){
if(!$gdate)$gdate=date("Y-m-d");
$w=date("w",strtotime($gdate));//取得一周的第几天,星期天开始0-6
$dn=$w?$w-$first:6;//要减去的天数
//本周开始日期
$st=date("Y-m-d",strtotime("$gdate-".$dn."days"));
//本周结束日期
$en=date("Y-m-d",strtotime("$st+6days"));
//上周开始日期
$last_st=date('Y-m-d',strtotime("$st-7days"));
//上周结束日期
$last_en=date('Y-m-d',strtotime("$st-1days"));
returnarray($st,$en,$last_st,$last_en);//返回开始和结束日期
}
echoimplode("|",aweek("",1)).'<br/>';
//echodate("Y-m-d",strtotime("time()"));
echo'本周第一天(星期日为一周开始):'.date('Y-m-d',time()-86400*date('w')).'<br/>';
echo'本周第一天(星期一为一周开始):'.date('Y-m-d',time()-86400*date('w')+(date('w')>0?86400:-6*86400)).'<br/>';
echo'本月第一天:'.date('Y-m-d',mktime(0,0,0,date('m'),1,date('Y'))).'<br/>';
echo'本月最后一天:'.date('Y-m-d',mktime(0,0,0,date('m'),date('t'),date('Y'))).'<br/>';
//上个月的开始日期
$m=date('Y-m-d',mktime(0,0,0,date('m')-1,1,date('Y')));
//上个月共多少天
$t=date('t',strtotime("$m"));
echo'上月第一天:'.date('Y-m-d',mktime(0,0,0,date('m')-1,1,date('Y'))).'<br/>';
echo'上月最后一天:'.date('Y-m-d',mktime(0,0,0,date('m')-1,$t,date('Y'))).'<br/>';
?></pre><p>PHP手册上有一个这个方法,用来返回指定日期的周一和周日</p><pre class="brush:php;toolbar:false"><?php
functionget_week_range($week,$year)
{
$timestamp=mktime(1,0,0,1,1,$year);
$firstday=date("N",$timestamp);
if($firstday>4)
$firstweek=strtotime('+'.(8-$firstday).'days',$timestamp);
else
$firstweek=strtotime('-'.($firstday-1).'days',$timestamp);
$monday=strtotime('+'.($week-1).'week',$firstweek);
$sunday=strtotime('+6days',$monday);
$start=date("Y-m-d",$monday);
$end=date("Y-m-d",$sunday);
returnarray($start,$end);
}
?></pre><p>strtotime获取本周第一天和最后一天方法的BUG</p><p>PHP手册上有一个这个方法,用来返回指定日期的周一和周日</p><pre class="brush:php;toolbar:false"><?php
functionget_week_range($week,$year)
{
$timestamp=mktime(1,0,0,1,1,$year);
$firstday=date("N",$timestamp);
if($firstday>4)
$firstweek=strtotime('+'.(8-$firstday).'days',$timestamp);
else
$firstweek=strtotime('-'.($firstday-1).'days',$timestamp);
$monday=strtotime('+'.($week-1).'week',$firstweek);
$sunday=strtotime('+6days',$monday);
$start=date("Y-m-d",$monday);
$end=date("Y-m-d",$sunday);
returnarray($start,$end);
}
?></pre><p>但在跨年的时候使用会有问题</p><p>例如2009年的12月31日周四和2010年1月1日周五周拿到的周一和周日完全不同</p><p>2009年12月31日拿合到的周一和周日分别对应</p><p>2009-12-28</p><p>2010-01-03</p><p>但2010年1月1日拿 到的周一和周日分别对应</p><p>2011-01-03</p><p>2011-01-09</p><p>原因为传进去的方法的周为第53周,但是年为2010年,所以认为2010的第53周,所以计算有误,解决方法为,如果周为大于10(因为一月个月不可能有10周),且月份为1的时候,将年减1处理</p><pre class="brush:php;toolbar:false">if(date('m',$last_week_time)=='01'and$tmp_last_week>10)
{
$last_week_year--;
}</pre>