JS獲取本週週一 週日日期、本季度、本月、上月的開端日期、停止日期

kongjiea發表於2015-07-10

1、首先來一個自己公司專案的原始碼:

專案需求描述: 從20150712日開始, ,

需求①:根據當前時間返回每一週 、週一~週日的日期(需返回2種格式 格式1:7月13日,格式2:2015-07-13)

需求②:返回當前時間本週的,週一早上9:00:00和週日的23:59:59

需求③:計算出當前時間離20150712日有多少周

需求④:在需求3基礎上,如果大於一週,需要返回歷史周的週一早上9:00:00和週日的23:59:59  (在此用二位陣列)

function GetWeekDate(time){
    var now = new Date(time); //當前日期 
    this.nowDayOfWeek = now.getDay(); //今天本週的第幾天
    this.nowYear = now.getYear(); //當前年 
    this.nowMonth = now.getMonth(); //月 
    this.nowDay = now.getDate(); //日 
    this.beginHour="09:00:00";
    this.endHour="23:59:59";

    this.nowYear += (this.nowYear < 2000) ? 1900 : 0; //
    this.nowDayOfWeek = this.nowDayOfWeek==0?7:this.nowDayOfWeek; // 如果是週日,就變成周七
}

GetWeekDate.prototype.date2str=function(x,y){//date2str(new Date(curTime),"yyyy-MM-dd")
    var z ={y:x.getFullYear(),M:x.getMonth()+1,d:x.getDate(),h:x.getHours(),m:x.getMinutes(),s:x.getSeconds()};  
    return y.replace(/(y+|M+|d+|h+|m+|s+)/g,function(v) {return ((v.length>1?"0":"")+eval('z.'+v.slice(-1))).slice(-(v.length>2?v.length:2))});  
}

GetWeekDate.prototype.formatDate=function(date){//格局化日期:yyyy-MM-dd 
    var myyear = date.getFullYear(); 
    var mymonth = date.getMonth()+1; 
    var myweekday = date.getDate();
    //alert("formatDate"+myyear+":"+mymonth+":"+myweekday)
    if(mymonth < 10){ 
        mymonth = "0" + mymonth; 
    } 
    if(myweekday < 10){ 
        myweekday = "0" + myweekday; 
    } 
    return (myyear+"-"+mymonth + "-" + myweekday); 
}

GetWeekDate.prototype.getWeekStartDate=function(){ //獲得本週的開端日期
    var weekStartDate = new Date(this.nowYear, this.nowMonth, this.nowDay - this.nowDayOfWeek+1);
    return this.formatDate(weekStartDate); 
}
 
GetWeekDate.prototype.getWeekEndDate=function(){//獲得本週的停止日期
    var weekEndDate = new Date(this.nowYear, this.nowMonth, this.nowDay + (6 - this.nowDayOfWeek+1));
    return this.formatDate(weekEndDate); 
}

GetWeekDate.prototype.getAWeedkYMD=function(){//獲得本週週一~週日的年月日
    var ymdArr=[];
    for (var i = 0; i < 7; i++) {
    	ymdArr[i]=[];
    	//ymdArr[i][0]=this.formatDate(new Date(this.nowYear, this.nowMonth, this.nowDay - this.nowDayOfWeek+i+1));
    	ymdArr[i][0]=this.date2str(new Date(this.nowYear, this.nowMonth, this.nowDay - this.nowDayOfWeek+i+1),'yyyy-MM-dd');
    	ymdArr[i][1]=this.date2str(new Date(this.nowYear, this.nowMonth, this.nowDay - this.nowDayOfWeek+i+1), 'MM月dd日');
    };
    
    return ymdArr;
}

GetWeekDate.prototype.getQishu=function(time){//獲得本週是指定日期(7.12日)的第幾周
    var oNDate=new Date(time); //系統當前時間
    var oEDate=new Date('2015/7/12 23:59:59');
    var diff= oNDate.getTime()-oEDate.getTime();
    //console.log(diff)
    //console.log("相差天:"+diff/(24*60*60*1000))
    //console.log("相差期數:"+parseInt(diff/(24*60*60*1000))/7)
    //console.log("取整期數:"+Math.floor(parseInt(diff/(24*60*60*1000))/7))
    return (diff/(24*60*60*1000))/7;
}

GetWeekDate.prototype.getWeeksDates=function(time){//獲取歷史周排行的週一到週日時間段
    var qishu = (this.qishu || this.qishu==0)?this.qishu:this.getQishu(time);
    //var qishu=this.getQishu(time);
    
    var WeeksTimes=[];//存放時間的二維陣列
        minYear=2015,
        minMonth=7,
        minDay=12;
    for (var i = 0; i<qishu; i++) {
        var sday;
        var eday;
        WeeksTimes[i]=[];
        if(i==0){//如果離2015-07-12只相差1期
            sday=minDay+1; //開始時間+1天
        }else{//如果離2015-07-12相差期數>1
            sday=minDay+1+7*i;
        }
        eday=minDay+7*(i+1);//結束時間+7天
        WeeksTimes[i][0]=this.formatDate(new Date(minYear,minMonth-1,sday))+" "+this.beginHour;
        WeeksTimes[i][1]=this.formatDate(new Date(minYear,minMonth-1,eday))+" "+this.endHour;
    };
    //如果是一週的週日就不要減去一期
    return WeeksTimes;
    
}

GetWeekDate.prototype.todayData=function(json){//處理tender_list_week.jsp頁面
    var oQishu=$('.qishu');
    	iQishu=this.qishu;//期數+1是因為,相差0期就是第1期
    	oThisWeekListBtn=$('.total_list_btn'),//檢視本週排行榜按鈕
    	sTime=this.getWeekStartDate()+" "+this.beginHour,
        eTime=this.getWeekEndDate()+" "+this.endHour;
    //1、修改期數
    	//console.log("相差周:"+iQishu);
	if(/^[1-9]\d*$/.test(iQishu) || iQishu==0){//整數 +3
    	oQishu.html(iQishu*1+3); 
    }else{
    	oQishu.html(Math.floor(iQishu)*1+4);
    }
    oThisWeekListBtn.attr("onclick","showWeekList('"+sTime+"','"+eTime+"')");//2、修改檢視本週排行榜的起止時間
}

GetWeekDate.prototype.historyData=function(time){//處理tender_list_week.jsp頁面
    var oQishu=$('.qishu'),
        oDateList=$('#dateList'), //頂部導航時間
        oHistoryList=$('#history_cont'),//歷史周
    	aThisWeekYMD=this.getAWeedkYMD(),//本週週一~週日的年月日
    	aThisWeekDates=this.getWeeksDates(time);//獲取歷史周排行的週一到週日時間段
    	iQishu=this.qishu;
    	//console.log("相差周:"+iQishu);
    
    //1、修改期數,+4是加上前3期,在+1是如果間隔3期,當前就是第4期
    	//如果時間23:59:59是正整數(-1),如果是0整數(3),如果是非整數(向下取整),或負數(向上取整)但是負數不考慮
    //oQishu.html(iQishu*1+3);
    if(/^[1-9]\d*$/.test(iQishu) || iQishu==0){//整數 +3
    	oQishu.html(iQishu*1+3); 
    }else{
    	oQishu.html(Math.floor(iQishu)*1+4);
    }
    
    
    //2、給頂部時間追加時間
    for (var i = 0; i < aThisWeekYMD.length; i++) {
    	var str='<li data-time="'+aThisWeekYMD[i][0]+'">'+aThisWeekYMD[i][1]+'</li>';
        $(str).appendTo(oDateList);
    };
    
    //3、給歷史周排行榜新增週期數
    if(this.qishu>1){//如果相差的期數大於1期
    	//console.dir(aThisWeekDates)
    	for (var j = 0; j < aThisWeekDates.length-1; j++) {
    		var iQiNum=j+4;
        	var str='<li onclick="showWeekList(\''+aThisWeekDates[j][0]+'\',\''+aThisWeekDates[j][1]+'\')">第'+iQiNum+'期</li>';
            $(str).prependTo(oHistoryList);
        };
    }
    
}

GetWeekDate.prototype.init=function(time){
    var iQishu=this.getQishu(time),//期數+1是因為,相差0期就是第1期
        json={};
    json.qishu=iQishu;
    this.qishu=iQishu;

    if($('#pageType').val()=="today"){//如果是tender_list_week.jsp頁面
    	if(new Date(time).getTime() < new Date('2015/07/12 23:59:59').getTime()){//特殊處理時間小於20150712
    		$('.qishu').html('3');
    		$('.total_list_btn').attr("onclick","showWeekList('2015-07-03 09:00:00','2015-07-12 23:59:59')");
    		return false;
    	}
        this.todayData(json);
    }else if($('#pageType').val()=="history"){
    	if(new Date(time).getTime() < new Date('2015/07/12 23:59:59').getTime()){//特殊處理時間小於20150712
    		$('.qishu').html('3');
    		$('#dateList').addClass('dateList2').html('<li data-time="2015-07-03">07月03日</li><li data-time="2015-07-04">07月04日</li><li data-time="2015-07-05">07月05日</li><li data-time="2015-07-06">07月06日</li><li data-time="2015-07-07">07月07日</li><li data-time="2015-07-08">07月08日</li><li data-time="2015-07-09">07月09日</li><li data-time="2015-07-10">07月10日</li><li data-time="2015-07-11">07月11日</li><li data-time="2015-07-12">07月12日</li>');
    		$('#history_cont').html('<li onclick="showWeekList(\'2015-06-26 09:00:00\',\'2015-07-02 23:59:59\')">第二期</li><li onclick="showWeekList(\'2015-06-19 12:00:00\',\'2015-06-25 23:59:59\')">第一期</li>');
    		return false;
    	}
        this.historyData(time);
    }
    //console.dir(this.getWeeksDates(time));
};
    


   

2、JS獲取本週、本季度、本月、上月的開端日期、停止日期

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>Document</title>
    <script src="http://apps.bdimg.com/libs/jquery/1.9.1/jquery.min.js"></script>
    <script>
    /**
* 日期範圍工具類
*/
var dateRangeUtil = (function () {
    /***
    * 獲得當前時間
    */
    this.getCurrentDate = function () {
        return new Date('2015','07','-1');
    };

    /***
    * 獲得本週起止時間
    */
    this.getCurrentWeek = function () {
        //起止日期陣列  
        var startStop = new Array();
        //獲取當前時間  
        var currentDate = this.getCurrentDate();
        //返回date是一週中的某一天  
        var week = currentDate.getDay();
        //返回date是一個月中的某一天  
        var month = currentDate.getDate();

        //一天的毫秒數  
        var millisecond = 1000 * 60 * 60 * 24;
        //減去的天數  
        var minusDay = week != 0 ? week - 1 : 6;
        //alert(minusDay);  
        //本週 週一  
        var monday = new Date(currentDate.getTime() - (minusDay * millisecond));
        //本週 週日  
        var sunday = new Date(monday.getTime() + (6 * millisecond));
        //新增本週時間  
        startStop.push(monday); //本週起始時間  
        //新增本週最後一天時間  
        startStop.push(sunday); //本週終止時間  
        //返回  
        return startStop;
    };

    /***
    * 獲得本月的起止時間
    */
    this.getCurrentMonth = function () {
        //起止日期陣列  
        var startStop = new Array();
        //獲取當前時間  
        var currentDate = this.getCurrentDate();
        //獲得當前月份0-11  
        var currentMonth = currentDate.getMonth();
        //獲得當前年份4位年  
        var currentYear = currentDate.getFullYear();
        //求出本月第一天  
        var firstDay = new Date(currentYear, currentMonth, 1);


        //當為12月的時候年份需要加1  
        //月份需要更新為0 也就是下一年的第一個月  
        if (currentMonth == 11) {
            currentYear++;
            currentMonth = 0; //就為  
        } else {
            //否則只是月份增加,以便求的下一月的第一天  
            currentMonth++;
        }


        //一天的毫秒數  
        var millisecond = 1000 * 60 * 60 * 24;
        //下月的第一天  
        var nextMonthDayOne = new Date(currentYear, currentMonth, 1);
        //求出上月的最後一天  
        var lastDay = new Date(nextMonthDayOne.getTime() - millisecond);

        //新增至陣列中返回  
        startStop.push(firstDay);
        startStop.push(lastDay);
        //返回  
        return startStop;
    };

    /**
    * 得到本季度開始的月份
    * @param month 需要計算的月份
    ***/
    this.getQuarterSeasonStartMonth = function (month) {
        var quarterMonthStart = 0;
        var spring = 0; //春  
        var summer = 3; //夏  
        var fall = 6;   //秋  
        var winter = 9; //冬  
        //月份從0-11  
        if (month < 3) {
            return spring;
        }

        if (month < 6) {
            return summer;
        }

        if (month < 9) {
            return fall;
        }

        return winter;
    };

    /**
    * 獲得該月的天數
    * @param year年份
    * @param month月份
    * */
    this.getMonthDays = function (year, month) {
        //本月第一天 1-31  
        var relativeDate = new Date(year, month, 1);
        //獲得當前月份0-11  
        var relativeMonth = relativeDate.getMonth();
        //獲得當前年份4位年  
        var relativeYear = relativeDate.getFullYear();

        //當為12月的時候年份需要加1  
        //月份需要更新為0 也就是下一年的第一個月  
        if (relativeMonth == 11) {
            relativeYear++;
            relativeMonth = 0;
        } else {
            //否則只是月份增加,以便求的下一月的第一天  
            relativeMonth++;
        }
        //一天的毫秒數  
        var millisecond = 1000 * 60 * 60 * 24;
        //下月的第一天  
        var nextMonthDayOne = new Date(relativeYear, relativeMonth, 1);
        //返回得到上月的最後一天,也就是本月總天數  
        return new Date(nextMonthDayOne.getTime() - millisecond).getDate();
    };

    /**
    * 獲得本季度的起止日期
    */
    this.getCurrentSeason = function () {
        //起止日期陣列  
        var startStop = new Array();
        //獲取當前時間  
        var currentDate = this.getCurrentDate();
        //獲得當前月份0-11  
        var currentMonth = currentDate.getMonth();
        //獲得當前年份4位年  
        var currentYear = currentDate.getFullYear();
        //獲得本季度開始月份  
        var quarterSeasonStartMonth = this.getQuarterSeasonStartMonth(currentMonth);
        //獲得本季度結束月份  
        var quarterSeasonEndMonth = quarterSeasonStartMonth + 2;

        //獲得本季度開始的日期  
        var quarterSeasonStartDate = new Date(currentYear, quarterSeasonStartMonth, 1);
        //獲得本季度結束的日期  
        var quarterSeasonEndDate = new Date(currentYear, quarterSeasonEndMonth, this.getMonthDays(currentYear, quarterSeasonEndMonth));
        //加入陣列返回  
        startStop.push(quarterSeasonStartDate);
        startStop.push(quarterSeasonEndDate);
        //返回  
        return startStop;
    };

    /***
    * 得到本年的起止日期
    * 
    */
    this.getCurrentYear = function () {
        //起止日期陣列  
        var startStop = new Array();
        //獲取當前時間  
        var currentDate = this.getCurrentDate();
        //獲得當前年份4位年  
        var currentYear = currentDate.getFullYear();

        //本年第一天  
        var currentYearFirstDate = new Date(currentYear, 0, 1);
        //本年最後一天  
        var currentYearLastDate = new Date(currentYear, 11, 31);
        //新增至陣列  
        startStop.push(currentYearFirstDate);
        startStop.push(currentYearLastDate);
        //返回  
        return startStop;
    };

    /**
    * 返回上一個月的第一天Date型別
    * @param year 年
    * @param month 月
    **/
    this.getPriorMonthFirstDay = function (year, month) {
        //年份為0代表,是本年的第一月,所以不能減  
        if (month == 0) {
            month = 11; //月份為上年的最後月份  
            year--; //年份減1  
            return new Date(year, month, 1);
        }
        //否則,只減去月份  
        month--;
        return new Date(year, month, 1); ;
    };

    /**
    * 獲得上一月的起止日期
    * ***/
    this.getPreviousMonth = function () {
        //起止日期陣列  
        var startStop = new Array();
        //獲取當前時間  
        var currentDate = this.getCurrentDate();
        //獲得當前月份0-11  
        var currentMonth = currentDate.getMonth();
        //獲得當前年份4位年  
        var currentYear = currentDate.getFullYear();
        //獲得上一個月的第一天  
        var priorMonthFirstDay = this.getPriorMonthFirstDay(currentYear, currentMonth);
        //獲得上一月的最後一天  
        var priorMonthLastDay = new Date(priorMonthFirstDay.getFullYear(), priorMonthFirstDay.getMonth(), this.getMonthDays(priorMonthFirstDay.getFullYear(), priorMonthFirstDay.getMonth()));
        //新增至陣列  
        startStop.push(priorMonthFirstDay);
        startStop.push(priorMonthLastDay);
        //返回  
        return startStop;
    };


    /**
    * 獲得上一週的起止日期
    * **/
    this.getPreviousWeek = function () {
        //起止日期陣列  
        var startStop = new Array();
        //獲取當前時間  
        var currentDate = this.getCurrentDate();
        //返回date是一週中的某一天  
        var week = currentDate.getDay();
        //返回date是一個月中的某一天  
        var month = currentDate.getDate();
        //一天的毫秒數  
        var millisecond = 1000 * 60 * 60 * 24;
        //減去的天數  
        var minusDay = week != 0 ? week - 1 : 6;
        //獲得當前周的第一天  
        var currentWeekDayOne = new Date(currentDate.getTime() - (millisecond * minusDay));
        //上週最後一天即本週開始的前一天  
        var priorWeekLastDay = new Date(currentWeekDayOne.getTime() - millisecond);
        //上週的第一天  
        var priorWeekFirstDay = new Date(priorWeekLastDay.getTime() - (millisecond * 6));

        //新增至陣列  
        startStop.push(priorWeekFirstDay);
        startStop.push(priorWeekLastDay);

        return startStop;
    };

    /**
    * 得到上季度的起始日期
    * year 這個年應該是運算後得到的當前本季度的年份
    * month 這個應該是運算後得到的當前季度的開始月份
    * */
    this.getPriorSeasonFirstDay = function (year, month) {
        var quarterMonthStart = 0;
        var spring = 0; //春  
        var summer = 3; //夏  
        var fall = 6;   //秋  
        var winter = 9; //冬  
        //月份從0-11  
        switch (month) {//季度的其實月份  
            case spring:
                //如果是第一季度則應該到去年的冬季  
                year--;
                month = winter;
                break;
            case summer:
                month = spring;
                break;
            case fall:
                month = summer;
                break;
            case winter:
                month = fall;
                break;

        };

        return new Date(year, month, 1);
    };

    /**
    * 得到上季度的起止日期
    * **/
    this.getPreviousSeason = function () {
        //起止日期陣列  
        var startStop = new Array();
        //獲取當前時間  
        var currentDate = this.getCurrentDate();
        //獲得當前月份0-11  
        var currentMonth = currentDate.getMonth();
        //獲得當前年份4位年  
        var currentYear = currentDate.getFullYear();
        //上季度的第一天  
        var priorSeasonFirstDay = this.getPriorSeasonFirstDay(currentYear, currentMonth);
        //上季度的最後一天  
        var priorSeasonLastDay = new Date(priorSeasonFirstDay.getFullYear(), priorSeasonFirstDay.getMonth() + 2, this.getMonthDays(priorSeasonFirstDay.getFullYear(), priorSeasonFirstDay.getMonth() + 2));
        //新增至陣列  
        startStop.push(priorSeasonFirstDay);
        startStop.push(priorSeasonLastDay);
        return startStop;
    };

    /**
    * 得到去年的起止日期
    * **/
    this.getPreviousYear = function () {
        //起止日期陣列  
        var startStop = new Array();
        //獲取當前時間  
        var currentDate = this.getCurrentDate();
        //獲得當前年份4位年  
        var currentYear = currentDate.getFullYear();
        currentYear--;
        var priorYearFirstDay = new Date(currentYear, 0, 1);
        var priorYearLastDay = new Date(currentYear, 11, 1);
        //新增至陣列  
        startStop.push(priorYearFirstDay);
        startStop.push(priorYearLastDay);
        return startStop;
    };
    return this;
    
})();

$(function(){

    $("#startDate").html( dateRangeUtil.getCurrentWeek() );
})

</script>
</head>
<body>
    <div id="startDate"></div>
</body>
</html>

3、JS獲取本週、本季度、本月、上月的開端日期、停止日期

Js程式碼   
/** 
* 獲取本週、本季度、本月、上月的開端日期、停止日期 
*/ 
var now = new Date(); //當前日期 
var nowDayOfWeek = now.getDay(); //今天本週的第幾天 
var nowDay = now.getDate(); //當前日 
var nowMonth = now.getMonth(); //當前月 
var nowYear = now.getYear(); //當前年 
nowYear += (nowYear < 2000) ? 1900 : 0; //

var lastMonthDate = new Date(); //上月日期 
lastMonthDate.setDate(1); 
lastMonthDate.setMonth(lastMonthDate.getMonth()-1); 
var lastYear = lastMonthDate.getYear(); 
var lastMonth = lastMonthDate.getMonth();

//格局化日期:yyyy-MM-dd 
function formatDate(date) { 
var myyear = date.getFullYear(); 
var mymonth = date.getMonth()+1; 
var myweekday = date.getDate();

if(mymonth < 10){ 
mymonth = "0" + mymonth; 
} 
if(myweekday < 10){ 
myweekday = "0" + myweekday; 
} 
return (myyear+"-"+mymonth + "-" + myweekday); 
}

//獲得某月的天數 
function getMonthDays(myMonth){ 
var monthStartDate = new Date(nowYear, myMonth, 1); 
var monthEndDate = new Date(nowYear, myMonth + 1, 1); 
var days = (monthEndDate - monthStartDate)/(1000 * 60 * 60 * 24); 
return days; 
}

//獲得本季度的開端月份 
function getQuarterStartMonth(){ 
var quarterStartMonth = 0; 
if(nowMonth<3){ 
quarterStartMonth = 0; 
} 
if(2<nowMonth && nowMonth<6){ 
quarterStartMonth = 3; 
} 
if(5<nowMonth && nowMonth<9){ 
quarterStartMonth = 6; 
} 
if(nowMonth>8){ 
quarterStartMonth = 9; 
} 
return quarterStartMonth; 
}

//獲得本週的開端日期 
function getWeekStartDate() { 
var weekStartDate = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek); 
return formatDate(weekStartDate); 
}

//獲得本週的停止日期 
function getWeekEndDate() { 
var weekEndDate = new Date(nowYear, nowMonth, nowDay + (6 - nowDayOfWeek)); 
return formatDate(weekEndDate); 
}

//獲得本月的開端日期 
function getMonthStartDate(){ 
var monthStartDate = new Date(nowYear, nowMonth, 1); 
return formatDate(monthStartDate); 
}

//獲得本月的停止日期 
function getMonthEndDate(){ 
var monthEndDate = new Date(nowYear, nowMonth, getMonthDays(nowMonth)); 
return formatDate(monthEndDate); 
}

//獲得上月開端時候 
function getLastMonthStartDate(){ 
var lastMonthStartDate = new Date(nowYear, lastMonth, 1); 
return formatDate(lastMonthStartDate); 
}

//獲得上月停止時候 
function getLastMonthEndDate(){ 
var lastMonthEndDate = new Date(nowYear, lastMonth, getMonthDays(lastMonth)); 
return formatDate(lastMonthEndDate); 
}

//獲得本季度的開端日期 
function getQuarterStartDate(){

var quarterStartDate = new Date(nowYear, getQuarterStartMonth(), 1); 
return formatDate(quarterStartDate); 
}

//或的本季度的停止日期 
function getQuarterEndDate(){ 
var quarterEndMonth = getQuarterStartMonth() + 2; 
var quarterStartDate = new Date(nowYear, quarterEndMonth, getMonthDays(quarterEndMonth)); 
return formatDate(quarterStartDate); 
} 



相關文章