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


当前回答

Moment.js可以消除处理Javascript Dates时的许多痛苦。

参见:http://momentjs.com/docs/#/displaying/unix-时间戳/

moment().unix();

其他回答

var time = Date.now || function() {
  return +new Date;
};

time();

Date.getTime()方法可以稍微调整一下:

getTime方法返回的值是毫秒数自1970年1月1日00:00:00 UTC开始。

将结果除以1000得到Unix时间戳,必要时为floor:

(new Date).getTime() / 1000

Date.valueOf()方法在功能上等同于Date.getTime(),这使得可以对Date对象使用算术运算符来获得相同的结果。在我看来,这种方法会影响可读性。

下面是另一个在JavaScript中生成时间戳的解决方案-包括单个数字的填充方法-在结果中使用天、月、年、小时、分钟和秒(jsfiddle的工作示例):

var pad = function(int) { return int < 10 ? 0 + int : int; };
var timestamp = new Date();

    timestamp.day = [
        pad(timestamp.getDate()),
        pad(timestamp.getMonth() + 1), // getMonth() returns 0 to 11.
        timestamp.getFullYear()
    ];

    timestamp.time = [
        pad(timestamp.getHours()),
        pad(timestamp.getMinutes()),
        pad(timestamp.getSeconds())
    ];

timestamp.now = parseInt(timestamp.day.join("") + timestamp.time.join(""));
alert(timestamp.now);

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

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

var timestamp = $.now();

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

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