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


当前回答

/**
 * Equivalent to PHP's time(), which returns
 * current Unix timestamp.
 *
 * @param  {string}  unit    - Unit of time to return.
 *                           - Use 's' for seconds and 'ms' for milliseconds.
 * @return {number}
 */
time(unit = 's') {
    return unit == 's' ? Math.floor(Date.now() / 1000) : Date.now()
}

其他回答

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

time();

对于lodash和下划线用户,请使用_.now。

var timestamp = _.now(); // in milliseconds
/**
 * Equivalent to PHP's time(), which returns
 * current Unix timestamp.
 *
 * @param  {string}  unit    - Unit of time to return.
 *                           - Use 's' for seconds and 'ms' for milliseconds.
 * @return {number}
 */
time(unit = 's') {
    return unit == 's' ? Math.floor(Date.now() / 1000) : Date.now()
}

日期,JavaScript中的原生对象是我们获取所有时间数据的方式。

在JavaScript中要小心,时间戳取决于客户端计算机设置,因此它不是100%准确的时间戳。要获得最佳结果,需要从服务器端获取时间戳。

总之,我更喜欢用香草。这是在JavaScript中实现的常见方法:

Date.now(); //return 1495255666921

在MDN中,如下所述:

Date.now()方法返回自1970年1月1日00:00:00 UTC。因为now()是Date的静态方法,所以您总是将其用作Date.now()。

如果您使用的版本低于ES5,Date.now();不起作用,您需要使用:

new Date().getTime();

这似乎奏效了。

console.log(clock.now);
// returns 1444356078076

console.log(clock.format(clock.now));
//returns 10/8/2015 21:02:16

console.log(clock.format(clock.now + clock.add(10, 'minutes'))); 
//returns 10/8/2015 21:08:18

var clock = {
    now:Date.now(),
    add:function (qty, units) {
            switch(units.toLowerCase()) {
                case 'weeks'   :  val = qty * 1000 * 60 * 60 * 24 * 7;  break;
                case 'days'    :  val = qty * 1000 * 60 * 60 * 24;  break;
                case 'hours'   :  val = qty * 1000 * 60 * 60;  break;
                case 'minutes' :  val = qty * 1000 * 60;  break;
                case 'seconds' :  val = qty * 1000;  break;
                default       :  val = undefined;  break;
                }
            return val;
            },
    format:function (timestamp){
            var date = new Date(timestamp);
            var year = date.getFullYear();
            var month = date.getMonth() + 1;
            var day = date.getDate();
            var hours = date.getHours();
            var minutes = "0" + date.getMinutes();
            var seconds = "0" + date.getSeconds();
            // Will display time in xx/xx/xxxx 00:00:00 format
            return formattedTime = month + '/' + 
                                day + '/' + 
                                year + ' ' + 
                                hours + ':' + 
                                minutes.substr(-2) + 
                                ':' + seconds.substr(-2);
            }
};