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


当前回答

您只能使用

var timestamp=new Date().getTime();console.log(时间戳);

以获取当前时间戳。不需要做任何额外的事情。

其他回答

JavaScript的工作时间是从纪元开始的毫秒数,而大多数其他语言的工作时间都是秒。您可以使用毫秒来工作,但只要您传递一个值来表示PHP,PHP本机函数可能就会失败。所以,为了确保我总是使用秒,而不是毫秒。

这将为您提供Unix时间戳(以秒为单位):

var unix = Math.round(+new Date()/1000);

这将为您提供自纪元以来的毫秒数(而不是Unix时间戳):

var milliseconds = new Date().getTime();

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

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

下面是一个生成时间戳的简单函数,格式为:mm/dd/yy hh:mi:ss

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

jQuery提供了自己的方法来获取时间戳:

var timestamp = $.now();

(此外,它还实现了(newDate).getTime()表达式)

裁判:http://api.jquery.com/jQuery.now/