js獲取選中日期的當周的週一和週日

剛找這個的js方法,找到了下面的博客:

https://www.cnblogs.com/nelsonlei/p/10071659.html

不知道爲什麼要把東西寫的這麼複雜。。。。

我自己寫了個:

function getDate(type,date){
    let d=date || new Date()
    let s=d.format("yyyy-MM-dd")
    if(type=="當天"){
        return [s,s]
    }else if(type=="本週"){
        let t=d.getTime()
        let day=d.getDay()
        day=day==0?7:day
        let d1= t-(day-1)*24*60*60*1000
        let d2= t+(7-day)*24*60*60*1000
        return [new Date(d1).format("yyyy-MM-dd"),new Date(d2).format("yyyy-MM-dd")]
    }else if(type=="本月"){
        let arr=s.split("-")
        return [arr[0]+"-"+arr[1]+"-01",arr[0]+"-"+arr[1]+"-"+run_nian(d)]
    }
}

let max_month=[1,3,5,7,8,10,12]
function run_nian(d){
    let month=d.getMonth()+1
    if(month==2){
        let year=d.getFullYear()
        if(year % 100 ==0){
            if(year % 400 ==0){
                return 29
            }
            return 28
        }else{
            return 28
        }
    }else{
        if($.inArray(month,max_month)>=0){
            return 31
        }else{
            return 30
        }
    }
}
/**
 * 日期格式化
 * @param {Object} fmt 格式化字符串,例:‘yyyy-MM-dd HH:mm:ss’
 */
Date.prototype.format = function(fmt) { //author: meizz
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //
        "H+": this.getHours(), //小時
        "m+": this.getMinutes(), //
        "s+": this.getSeconds(), //
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : ((
            "00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

當然我這個複雜是有三種,單個的比那個簡單多了。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章