【问题标题】:How to use javascript to create a string of numbers based on current time?如何使用javascript根据当前时间创建一串数字?
【发布时间】:2014-03-02 05:54:37
【问题描述】:

我曾经使用代码为我的文件名创建一串数字以避免重复。它的作用是向我发送一串非常准确的当前时间的数字(例如 1/1000000000 秒)。我不记得我是怎么做到的了,因为我只是复制和粘贴我的旧代码。有人知道怎么做吗?

【问题讨论】:

  • new Date().getTime() 返回Integer value representing the number of milliseconds since 1 January 1970 00:00:00 UTC (Unix Epoch).

标签: javascript timestamp


【解决方案1】:

在 MDN 上有一个关于 Javascript Date 构造函数/对象的很好的参考资料。但基本上,在较旧的环境中,这样做。

new Date().getTime()

在较新的环境中您可以这样做

Date.now()

两者都返回Integer value representing the number of milliseconds since 1 January 1970 00:00:00 UTC (Unix Epoch).

你也可以这样做

new Date().valueOf()

但它可能不如上述可靠。

【讨论】:

    【解决方案2】:

    您可以使用 Date 对象的 getTime 方法创建检索自纪元以来经过的毫秒数。

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

    【讨论】:

    • A Unix timestamp 不同。the number of seconds that have elapsed since 00:00:00 Coordinated Universal Time (UTC), Thursday, 1 January 1970。您必须将 javascript 时间戳除以 1000 才能获得秒数。
    • 你是对的,这是错误的术语,我正在更新答案。
    【解决方案3】:

    javascript 中的当前时间仅提供毫秒数。如果一次生成多个文件名,您可能会在同一操作中多次请求时获得相同的当前时间。因此,如果您想要一个完全唯一的数字(比当前毫秒更具唯一性,因此您可以在紧密循环中生成其中的一些数字),您可以将时间与随机生成的值结合起来,如下所示:

    function makeUnique(base) {
        var now = new Date().getTime();
        var random = Math.floor(Math.random() * 100000);
        return base + now + random;
    }
    
    makeUnique("test");
    

    工作演示:http://jsfiddle.net/jfriend00/dpZLC/

    如果您希望文件名始终是相同的位数,您可以像这样对随机数进行零填充:

    function makeUnique(base) {
        var now = new Date().getTime();
        var random = Math.floor(Math.random() * 100000);
        // zero pad random
        random = "" + random;
        while (random.length < 5) {
            random = "0" + random;
        }
        return base + now + random;
    }
    

    【讨论】:

      猜你喜欢
      • 2017-01-05
      • 1970-01-01
      • 1970-01-01
      • 2014-01-06
      • 2011-12-22
      • 1970-01-01
      • 2023-01-11
      • 1970-01-01
      • 2020-07-10
      相关资源
      最近更新 更多