JavaScript时间相关的方法

总结JavaScript获取时间相关的方法,以备日后不时之需。

1, 得到定制格式的当前时间;

function getNowDate() {
    var date = new Date();
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    var curDate = date.getFullYear() + '-' + month + '-' + strDate
            + " " + date.getHours() + ':' + date.getMinutes()
            + ':' + date.getSeconds();
    return curDate;
}

 

2,得到当前时间戳;

Date.now();
//或者
new Date().getTime();
// 或者
+new Date();

 

3,得到周几(周日为0);

new Date().getDay();

 

4,获得今天的前一天;

var curDate = new Date();
var preDate = new Date(curDate.getTime() - 24*60*60*1000); 

 

posted @ 2019-04-03 14:42  贾各布  阅读(259)  评论(0编辑  收藏  举报