℡Wang Yan 2008-10-21 09:29 采纳率: 100%
浏览 620
已采纳

在 JavaScript 中如何获得时间戳?

How can I get a timestamp in JavaScript?

Something similar to Unix's timestamp, that is, a single number that represents the current time and date. Either as a number or a string.

转载于:https://stackoverflow.com/questions/221294/how-do-you-get-a-timestamp-in-javascript

  • 写回答

30条回答 默认 最新

  • 旧行李 2008-10-21 09:32
    关注

    Short & Snazzy:

    + new Date()
    

    A unary operator like plus triggers the valueOf method in the Date object and it returns the timestamp (without any alteration).

    Details:

    On almost all current browsers you can use Date.now() to get the UTC timestamp in milliseconds; a notable exception to this is IE8 and earlier (see compatibility table).

    You can easily make a shim for this, though:

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

    To get the timestamp in seconds, you can use:

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

    Or alternatively you could use:

    Date.now() / 1000 | 0
    

    Which should be slightly faster, but also less readable (also see this answer).

    I would recommend using Date.now() (with compatibility shim). It's slightly better because it's shorter & doesn't create a new Date object. However, if you don't want a shim & maximum compatibility, you could use the "old" method to get the timestamp in milliseconds:

    new Date().getTime()
    

    Which you can then convert to seconds like this:

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

    And you can also use the valueOf method which we showed above:

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

    </div>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(29条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题