日期:2014-05-16  浏览次数:20393 次

计算日期为当年的第几周(javascript)
早期写个一个算法,虽然写的不是很好,但挺有用的,拿出来分享一下
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题 1</title>
<script type="text/javascript">

function shipweek(datestr)
{
var datestr=datestr;

var strdate=datestr.split(" ")[0];
strdate=strtodateline(strdate);
var shipweek;
var numdate=strdate.getTime();
var nowyear=strdate.getYear();
var firstday=new Date(nowyear,0,1);

if((firstday.getDay()<5)&(firstday.getDay()!=0)){
firstday.setTime(firstday.getTime()-firstday.getDay()*24*60*60*1000);}
else{ if(firstday.getDay()==0){firstday.setTime(firstday.getTime()+0*24*60*60*1000);}
else{firstday.setTime(firstday.getTime()+(7-firstday.getDay())*24*60*60*1000);}
}
var lastday=new Date(nowyear,11,31);

var weeknum=Math.ceil((strdate.getTime()-firstday.getTime())/(7*24*60*60*1000));

if((weeknum<10)&(weeknum!=0)){shipweek="Y"+nowyear+"W0"+weeknum;}
else{shipweek="Y"+nowyear+"W"+weeknum;}


if(weeknum == 0){

   if(shipweek2((nowyear-1)+"-"+12+"-"+31)==53){
    if(strdate.getMonth()==0){
    shipweek="Y"+eval(nowyear-1)+"W53";
    }else
    {
    shipweek="Y"+nowyear+"W53";
    }
    }
   else{
    if(strdate.getMonth()==0){
    shipweek="Y"+eval(nowyear-1)+"W52";
    }else{
    shipweek="Y"+nowyear+"W52";
    }
    }
   }

if(weeknum>52){

if(lastday.getDay()>3){
   weeknum=53;
   if(strdate.getMonth()==0){
   shipweek="Y"+eval(nowyear-1)+"W"+weeknum;
    }
   else{
   shipweek="Y"+nowyear+"W"+weeknum;
    }
 
   }
else{
   shipweek="Y"+eval(nowyear+1)+"W01";
   }

}


return shipweek;

}

function shipweek2(datestr)
{
var datestr=datestr;
var strdate=datestr;
strdate=strtodateline(strdate);

var shipweek;
var numdate=strdate.getTime();
var nowyear=strdate.getYear();
var firstday=new Date(nowyear,0,1);

if((firstday.getDay()<5)&(firstday.getDay()!=0)){
firstday.setTime(firstday.getTime()-firstday.getDay()*24*60*60*1000);}
else{firstday.setTime(firstday.getTime()+(7-firstday.getDay())*24*60*60*1000);}


var lastday=new Date(nowyear,11,31);

var weeknum=Math.ceil((strdate.getTime()-firstday.getTime())/(7*24*60*60*1000));

if((weeknum<10)&(weeknum!=0)){shipweek=weeknum;}
else{shipweek=weeknum;}

if(weeknum == 0){shipweek=53;}

if(weeknum>52){
if(lastday.getDay()>3){
   weeknum=53; 
   shipweek=weeknum;
   }
else{
   shipweek=1;
   }

}


return shipweek;

}


//***********************
function shipMonth(datestr)
{
var datestr=datestr;

var strdate=datestr.split(" ")[0];
strdate=strtodateline(strdate);
var shipweek;
var numdate=strdate.getTime();
var nowyear=strdate.getYear();
var nowmonth=strdate.getMonth();

var firstday=new Date(nowyear,nowmonth,1);


if((firstday.getDay(