JavaScript获取时间戳的坑

本文介绍了JavaScript获取时间戳的三种方法,包括Date.parse(new Date())、(new Date()).valueOf()和new Date().getTime(),并指出这些方法可能因客户端时区差异导致时间戳不准确的问题。在实际应用中,需要注意客户端时间设置可能带来的误差。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

JavaScript获取时间戳的三个方法:

  • Date.parse(new Date())
    获取13位时间戳,例如1553581293000,
  • (new Date()).valueOf()
    获取13位时间戳,精确到毫秒,例如:1553581461549
  • new Date().getTime()。
    获取13位时间戳,精确到毫秒,例如:1553581482325

示例

以上面第一种方法为例

<!DOCTYPE html>
<html>

<body>
    <p id="demo">timestamp</p>
    <button type="button" onclick="myFunction()">点击这里,显示时间戳</button>

    <script>
        function myFunction() {
            document.getElementById("demo").innerHTML = Date.parse(new Date());
        }
    </script>

</body>

</html>

上述页面中的脚本执行后,会返回13位数字,如:1553581461549。parse方法会解析包含日期的字符串,并返回该日期与1970年1月1日午夜之间的毫秒数(UTC时间)。而上面parse解析的字符串是通过new Date()方法来获取到的,从下面的内容来看,new Date()获取的是一个当前主机的本地时间。

/** Enables basic storage and retrieval of dates and times. */
interface Date {
    /** Returns a string representation of a date. The format of the string depends on the locale. */
    toString(): string;
    /** Returns a date as a string value. */
    toDateString(): string;
    /** Returns a time as a string value. */
    toTimeString(): string;
    /** Returns a value as a string value appropriate to the host environment's current locale. */
    toLocaleString(): string;
    /** Returns a date as a string value appropriate to the host environment's current locale. */
    toLocaleDateString(): string;
    /** Returns a time as a string value appropriate to the host environment's current locale. */
    toLocaleTimeString(): string;
    /** Returns the stored time value in milliseconds since midnight, January 1, 1970 UTC. */
    valueOf(): number;
    /** Gets the time value in milliseconds. */
    getTime(): number;
    /** Gets the year, using local time. */
    getFullYear(): number;
    /** Gets the year using Universal Coordinated Time (UTC). */
    getUTCFullYear(): number;
    /** Gets the month, using local time. */
    getMonth(): number;
   
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值