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


当前回答

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

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

其他回答

console.log(newDate().valueOf());//返回自epoch以来的毫秒数

我强烈建议使用moment.js

moment().valueOf()

要获取自UNIX纪元以来的秒数,请执行

moment().unix()

也可以这样转换时间:

moment('2015-07-12 14:59:23', 'YYYY-MM-DD HH:mm:ss').valueOf()

我一直这么做。没有双关语。

要在浏览器中使用moment.js:

<script src="moment.js"></script>
<script>
    moment().valueOf();
</script>

有关更多详细信息,包括安装和使用MomentJS的其他方式,请参阅他们的文档

简单来说,这里有一个函数可以在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;
}
function getTimeStamp() {
    var now = new Date();
    return ((now.getMonth() + 1) + '/' +
            (now.getDate()) + '/' +
             now.getFullYear() + " " +
             now.getHours() + ':' +
             ((now.getMinutes() < 10)
                 ? ("0" + now.getMinutes())
                 : (now.getMinutes())) + ':' +
             ((now.getSeconds() < 10)
                 ? ("0" + now.getSeconds())
                 : (now.getSeconds())));
}

这一个有一个解决方案:在js中将unixtime stamp转换为tim

var a = new Date(UNIX_timestamp*1000);
var hour = a.getUTCHours();
var min = a.getUTCMinutes();
var sec = a.getUTCSeconds();