我想要一个表示当前日期和时间的数字,比如Unix时间戳。


当前回答

要分别获得时间、月、日、年,这将起作用

var currentTime = new Date();
var month = currentTime.getMonth() + 1;
var day = currentTime.getDate();
var year = currentTime.getFullYear();

其他回答

简单来说,这里有一个函数可以在Javascript中返回时间戳字符串。示例:下午15:06:38

function displayTime() {
    var str = "";

    var currentTime = new Date()
    var hours = currentTime.getHours()
    var minutes = currentTime.getMinutes()
    var seconds = currentTime.getSeconds()

    if (minutes < 10) {
        minutes = "0" + minutes
    }
    if (seconds < 10) {
        seconds = "0" + seconds
    }
    str += hours + ":" + minutes + ":" + seconds + " ";
    if(hours > 11){
        str += "PM"
    } else {
        str += "AM"
    }
    return str;
}
time = Math.round(((new Date()).getTime()-Date.UTC(1970,0,1))/1000);

要分别获得时间、月、日、年,这将起作用

var currentTime = new Date();
var month = currentTime.getMonth() + 1;
var day = currentTime.getDate();
var year = currentTime.getFullYear();

任何不支持Date.now的浏览器,您都可以使用它获取当前日期时间:

currentTime = Date.now() || +new Date()

有时我需要在xmlhttp调用的对象中使用它,所以我喜欢这样做。

timestamp : parseInt(new Date().getTime()/1000, 10)