JS獲取時間日期常用方法


1 當前時間:

new Date()

2 當前周:

function getCurrentWeek() {
    var date = new Date()
    var beginDate = new Date(date.getFullYear(), 0, 1);
    var week = Math.ceil((parseInt((date - beginDate) / (24 * 60 * 60 * 1000)) + 1 + beginDate.getDay()) / 7);
    return week;
}

3 當前月(獲取的月份值范圍為:0-11,0表示1月份):

new Date().getMonth()

4 當前年(注意與getYear的區別):

new Date().getFullYear()

5 當前星期幾

function getWeekDate() {
       var now = new Date();
       var day = now.getDay();
       var weeks = new Array("星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六");
       var week = weeks[day];
       return week;
    }

6 日期格式化

Date.prototype.format = function (fmt) {
    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;
}

使用方法:

new Date().format("yyyy-MM-dd hh:mm:ss");

7 一年有多少周

function getTotalWeek(year) {
    // 一年第一天是周幾
    var first = new Date(year,0,1).getDay()
    // 計算一年有多少天
    if((year % 4 == 0 && year % 100 != 0) || (year % 100 == 0 && year % 400 == 0)) {
        var allyears = 366
    }else {
        var allyears = 365
    }
    // 計算一年有多少周
    var week = parseInt((allyears + first) / 7)
    if(((allyears + first) % 7) != 0) {
        week += 1
    }
    return week
}

8 當月有多少天

function getCountDays() {
          var curDate = new Date();
        /* 獲取當前月份 */
          var curMonth = curDate.getMonth();
        /*  生成實際的月份: 由於curMonth會比實際月份小1, 故需加1 */
        curDate.setMonth(curMonth + 1);
        /* 將日期設置為0, 這里為什么要這樣設置, 我不知道原因, 這是從網上學來的 */
        curDate.setDate(0);
        /* 返回當月的天數 */
        return curDate.getDate();
}

持續更新中。。。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM