首页 文章

你如何获得JavaScript的时间戳?

提问于
浏览
3502

如何在JavaScript中获取时间戳?

与Unix的时间戳类似的东西,即代表当前时间和日期的单个数字 . 无论是数字还是字符串 .

30 回答

  • 38

    jQuery提供its own method来获取时间戳:

    var timestamp = $.now();
    

    (除了它实现(new Date).getTime()表达式)

    REF: http://api.jquery.com/jQuery.now/

  • 33
    console.log(new Date().valueOf()); // returns the number of milliseconds since the epoch
    
  • 18

    Date.getTime()方法可以使用一点点调整:

    getTime方法返回的值是自1970年1月1日00:00:00 UTC以来的毫秒数 .

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

    (new Date).getTime() / 1000
    

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

  • 53

    更简单的方法:

    var timeStamp=event.timestamp || new Date().getTime();
    
  • 18

    Moment.js可以抽象出很多处理Javascript日期的痛苦 .

    见:http://momentjs.com/docs/#/displaying/unix-timestamp/

    moment().unix();
    
  • 12

    我喜欢这个,因为它很小:

    +new Date
    

    我也喜欢这个,因为它与现代浏览器一样短,并且与现代浏览器兼容,超过500人投票表示它更好:

    Date.now()
    
  • 6

    I provide multiple solutions with descriptions in this answer. Feel free to ask questions if anything is unclear
    PS:遗憾的是有人将此合并到最佳答案而没有给予信任 .


    Quick and dirty solution:

    Date.now() /1000 |0
    

    警告:它可能在2038年中断并且如果你执行| 0魔法则返回负数 . 使用Math.floor()代替那个时间

    Math.floor() solution:

    Math.floor(Date.now() /1000);
    

    Some nerdy alternative by Derek 朕會功夫 taken from the comments below this answer:

    new Date/1e3|0
    

    Polyfill to get Date.now() working:

    要使它在IE中工作,你可以这样做(Polyfill来自MDN):

    if (!Date.now) {
        Date.now = function now() {
            return new Date().getTime();
        };
    }
    

    If you do not care about the year / day of week / daylight saving time you could strip it away and use this after 2038:

    var now = (function () {
        var year = new Date(new Date().getFullYear().toString()).getTime();
        return function () {
            return Date.now() - year
        }
    })();
    

    它的外观有些输出:new Date()
    星期四2015年10月29日08:46:30 GMT 0100(MitteleuropäischeZeit)
    新日期(现在())
    Thu Oct 29 1970 09:46:30 GMT 0100(MitteleuropäischeZeit)
    当然它会打破夏令时但是根据你正在构建的内容,如果你需要在时间戳上执行二进制操作,在int32将在2038年中断之后,这可能对你有用 . 这也将返回负值,但仅当用户为正在运行代码的PC正在将PC的时钟改变为至少去年12月31日 .


    如果您只想知道从代码运行到第一次的相对时间,您可以使用以下内容:

    var relativeTime = (function () {
        var start = Date.now();
        return function () {
            return Date.now() - start
        }
    })();
    

    In case you are using jQuery you could use $.now() as described in jQuery's Docs which makes the polyfill obsolete since $.now() internally does the same thing: (new Date).getTime()

    如果您对jQuery的版本感到高兴,请考虑提高this答案,因为我自己并没有找到它 .


    Now a tiny explaination of what |0 does:

    通过提供 | ,您告诉解释器执行二进制OR操作 . 位操作需要绝对数字,将小数结果从 Date.now() / 1000 变为整数 .

    在该转换期间,删除小数,导致与使用 Math.floor() 但使用较少代码相同的结果 .

    但要注意:它会将64位双精度转换为32位整数 . 这会在处理大量数据时导致信息丢失 . 由于32位整数溢出,时间戳将在2038年后中断 .


    For further information about Date.now follow this link: Date.now() @ MDN

  • 12

    这个有一个解决方案:在js中将unixtime标记转换为tim尝试这个

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

    前几天我从JQuery Cookie的源代码中学习了一种将给定Date对象转换为Unix时间戳的非常酷的方法 .

    这是一个例子:

    var date = new Date();
    var timestamp = +date;
    
  • 4329

    除了其他选项,如果你想要一个dateformat ISO,你可以直接得到它

    console.log(new Date().toISOString());
    
  • 11
    var timestamp = Number(new Date()); // current time as number
    
  • 76
    var time = Date.now || function() {
      return +new Date;
    };
    
    time();
    
  • 8

    一个我还没有看到的

    Math.floor(Date.now() / 1000); // current time in seconds
    

    另一个我还没有看到的是

    var _ = require('lodash'); // from here https://lodash.com/docs#now
    _.now();
    
  • 130

    在写这篇文章时,最重要的答案是9年,从那以后发生了很多变化 - 尤其是,我们几乎普遍支持非hacky解决方案:

    Date.now()
    

    如果你想绝对肯定这不会在一些古老的(pre ie9)浏览器中破坏,你可以把它放在支票后面,如下:

    const currentTimestamp = (!Date.now ? +new Date() : Date.now());
    

    这将返回自纪元时间以来的毫秒,当然,不是秒 .

    MDN Documentation on Date.now

  • 107

    短&时髦:

    + new Date()
    

    plus 这样的一元运算符会触发 Date 对象中的 valueOf 方法,并返回时间戳(不做任何更改) .

    Details:

    在几乎所有当前浏览器上,您都可以使用Date.now()来获取 milliseconds 中的UTC时间戳;一个值得注意的例外是IE8及更早版本(参见compatibility table) .

    不过,你可以很容易地为此做一个垫片:

    if (!Date.now) {
        Date.now = function() { return new Date().getTime(); }
    }
    

    要获取 seconds 中的时间戳,您可以使用:

    Math.floor(Date.now() / 1000)
    

    或者您也可以使用:

    Date.now() / 1000 | 0
    

    哪个应该稍快,但也不太可读(也是see this answer) .

    我建议使用 Date.now() (兼容垫片) . 它's slightly better because it'更短并且不会创建新的 Date 对象 . 但是,如果您不想要垫片和最大兼容性,可以使用"old"方法获取 milliseconds 中的时间戳:

    new Date().getTime()
    

    然后您可以将其转换为秒,如下所示:

    Math.round(new Date().getTime()/1000)
    

    你也可以使用我们上面显示的 valueOf 方法:

    new Date().valueOf()
    

    Timestamp in Milliseconds

    var timeStampInMs = window.performance && window.performance.now && window.performance.timing && window.performance.timing.navigationStart ? window.performance.now() + window.performance.timing.navigationStart : Date.now();
    
    console.log(timeStampInMs, Date.now());
    
  • 26

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

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

    Date JavaScript中的本机对象是我们获取所有时间数据的方式 .

    在JavaScript中要小心,时间戳取决于客户端计算机设置,因此它不是100%准确的时间戳 . 为了获得最佳结果,您需要从 server-side 获取时间戳 .

    无论如何,我的首选方式是使用香草 . 这是在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();
    
  • 451

    我强烈建议使用 moment.js . 要获得自UNIX纪元以来的毫秒数,请执行此操作

    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的其他方法,请参阅docs

  • 11

    对于具有微秒分辨率的时间戳,有performance.now

    function time() { 
      return performance.now() + performance.timing.navigationStart;
    }
    

    例如,这可以产生 1436140826653.139 ,而 Date.now 只能产生 1436140826653 .

  • 16

    这是一个生成时间戳的简单函数,格式为: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())));
    }
    
  • 25

    你只能使用

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

    获取当前时间戳 . 无需做任何额外的事情 .

  • 23

    如果想要一种在Node.js中生成时间戳的基本方法,这种方法很有效 .

    var time = process.hrtime();
    var timestamp = Math.round( time[ 0 ] * 1e3 + time[ 1 ] / 1e6 );
    

    我们的团队正在使用它来在本地主机环境中破解缓存 . 输出为 /dist/css/global.css?v=245521377 ,其中 245521377hrtime() 生成的时间戳 .

    希望这有帮助,上面的方法也可以工作,但我发现这是我们在Node.js中最简单的方法 .

  • 241

    这似乎有效 .

    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);
                }
    };
    
  • 8

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

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

    代码 Math.floor(new Date().getTime() / 1000) 可以缩短为 new Date / 1E3 | 0 .

    考虑跳过直接getTime()调用并使用 | 0 替换Math.floor()函数 . 记住 1E31000 的较短等价物也是一件好事(大写E优于小写,表示 1E3 为常数) .

    因此,您将获得以下信息:

    var ts = new Date / 1E3 | 0;
    
    console.log(ts);
    
  • 18

    今天 - 2018.06.27我提供了纯js解决方案的时间比较 . 这对于想要以轻/高效方式获取/测量JS时间的人来说非常有用(例如,对于模拟,游戏等实时应用程序)

    在Chrome 67.0.3396.99(64位),Safari 11.0.3(13604.5.6),Firefox 59.0.2(64位)上的MacOs High Sierra 10.13.3上进行了测试 . 在下面的屏幕截图中,我展示了最快浏览器(Safari)的结果:

    我观察到 Date.now() 是获取所有三种浏览器时间戳的最快方法 . Safari每秒运行19.2M,Firefox 16.1M,Chrome 7.8M .

    new Date()*1 对于Chrome(2.8M)和Firefox(2.6M)来说是最慢的 . Number(new Date()) 对Safari来说是最慢的(2.9M) .

    So the winner JS code is Date.now() and fastest browser is Safari (2x faster that chrome! ).

    您可以在此处对您的机器进行测试:https://jsperf.com/timestamp-test-x .

  • 10

    JavaScript使用自纪元以来的毫秒数,而大多数其他语言使用秒 . 您可以使用毫秒,但只要您传递一个值来表示PHP,PHP本机函数可能会失败 . 所以要确保我总是使用秒,而不是毫秒 .

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

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

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

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

    只是为了加起来,这是一个在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;
    }
    
  • 23
    // The Current Unix Timestamp
    // 1443534720 seconds since Jan 01 1970. (UTC)
    
    // seconds
    console.log(Math.floor(new Date().valueOf() / 1000)); // 1443534720
    console.log(Math.floor(Date.now() / 1000)); // 1443534720
    console.log(Math.floor(new Date().getTime() / 1000)); // 1443534720
    
    // milliseconds
    console.log(Math.floor(new Date().valueOf())); // 1443534720087
    console.log(Math.floor(Date.now())); // 1443534720087
    console.log(Math.floor(new Date().getTime())); // 1443534720087
    
    // jQuery
    // seconds
    console.log(Math.floor($.now() / 1000)); // 1443534720
    // milliseconds
    console.log($.now()); // 1443534720087
    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
  • 5

    对于lodashunderscore用户,请使用 _.now .

    var timestamp = _.now(); // in milliseconds
    

相关问题