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();

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

new Date().getDay();

4,获得今天的前一天;

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

扫描二维码关注公众号,回复: 5762686 查看本文章

猜你喜欢

转载自www.cnblogs.com/easonw/p/10648710.html