【问题标题】:How to get the current date or/and time in seconds以秒为单位获取当前日期/时间
【发布时间】:2011-04-19 07:37:32
【问题描述】:

如何在 Javascript 中以秒为单位获取当前日期/时间?

【问题讨论】:

标签: javascript datetime


【解决方案1】:
var seconds = new Date().getTime() / 1000;

....将为您提供自 1970 年 1 月 1 日午夜以来的秒数

Reference

【讨论】:

  • 虽然这是准确的,但它什么时候有用? :)
  • @Nick - 我认为所有示例都必然是推测性的,而且听起来很做作 - 但我会试一试:) 假设您有数据时间戳,带有 unix 时间,并且想要确定它的年龄。虽然我认为这很可能是“当前日期/时间(以秒为单位)”的意思;只是我的直觉。
  • 我需要这个的应用程序是与 PHP 后端一起工作,因为 time() 函数已经返回了这个。它也非常适合时间戳,因为您可以很容易地得到 time() 是我们当前时间和以前存储在数据库中的时间戳之间的差异,比如用户发布内容时。如果您想获得像“2015 年 10 月 22 日”这样的格式化时间,您可以制作自己的函数以将时间戳作为参数返回,或者使用 Stack 中已有的时间。无论如何,希望这能给您一些关于何时有用的见解。 @NickCraver
  • 值得注意的是,你想把它包装在 Math.floor() 中,否则你会得到一个小数。
  • 一种有用的方法是计算两次之间经过的时间。
【解决方案2】:
 Date.now()

给出自纪元以来的毫秒数。无需使用new

在此处查看参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now

(IE8 不支持。)

【讨论】:

  • 这个毫秒的答案甚至没有回答被问到的问题。 "如何以秒为单位获取当前日期/时间"
  • Date.now() / 1000 自己回答问题
  • @magician11 - Date.now() / 1000 也没有回答这个问题,因为它给出了以毫秒为单位的部分分数的值
【解决方案3】:

使用new Date().getTime() / 1000 是获取秒数的不完整解决方案,因为它会生成带有浮点单位的时间戳。

new Date() / 1000; // 1405792936.933

// Technically, .933 would be in milliseconds

改为使用:

Math.round(Date.now() / 1000); // 1405792937

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

// Or
Math.ceil(Date.now() / 1000); // 1405792937

// Note: In general, I recommend `Math.round()`,
//   but there are use cases where
//   `Math.floor()` and `Math.ceil()`
//   might be better suited.

此外,没有浮点数的值对于条件语句更安全,因为使用浮点数获得的粒度可能会导致不需要的结果。例如:

if (1405792936.993 < 1405792937) // true

警告:位运算符在用于处理时间戳时可能会导致问题。例如,(new Date() / 1000) | 0 也可用于将值“下限”为秒,但该代码会导致以下问题:

  1. 默认情况下,Javascript 数字是 64 位(双精度)浮点类型,按位运算符将该类型隐式转换为带符号的 32 位整数。可以说,编译器不应隐式转换类型,而应由开发人员在需要时进行转换。
  2. 按位运算符生成的带符号的 32 位整数时间戳会导致 year 2038 问题,如 cmets 中所述。

【讨论】:

  • 完全同意?使用Math.round(new Date() / 1000)
  • 请注意,使用按位运算符取整会导致值转换为有符号的 32 位整数。见Year 2038 problem
  • @Ryan - 谢谢我更新了我的答案以阻止使用| 0
  • 为什么是Math.round 而不是Math.floor/Math.trunc
  • @AndreFigueiredo - 感谢您提供这些示例。我提供的解决方案是针对“如何在 Javascript 中以秒为单位获取当前日期/时间?”的问题,因此您以小时为单位的示例不在上下文中,但我认为您以秒为单位的示例具有一定的有效性。总的来说,我仍然认为Math.round() 是最好的。但是,是的,我同意有些用例不是最好的,Math.floor()Math.ceil() 更合适。我已经更新了我的答案以说明相同的内容。
【解决方案4】:

根据您的评论,我认为您正在寻找这样的东西:

var timeout = new Date().getTime() + 15*60*1000; //add 15 minutes;

那么在你的检查中,你正在检查:

if(new Date().getTime() > timeout) {
  alert("Session has expired");
}

【讨论】:

    【解决方案5】:

    要获取 Javascript 纪元的秒数​​,请使用:

    date = new Date();
    milliseconds = date.getTime();
    seconds = milliseconds / 1000;
    

    【讨论】:

      【解决方案6】:

      // The Current Unix Timestamp
      // 1443535752 seconds since Jan 01 1970. (UTC)
      
      // Current time in seconds
      console.log(Math.floor(new Date().valueOf() / 1000));  // 1443535752
      console.log(Math.floor(Date.now() / 1000));            // 1443535752
      console.log(Math.floor(new Date().getTime() / 1000));  // 1443535752
      &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;

      jQuery

      console.log(Math.floor($.now() / 1000));               // 1443535752
      &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;

      【讨论】:

        【解决方案7】:

        我用这个:

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

        无需创建新对象(请参阅doc Date.now()

        【讨论】:

          【解决方案8】:

          这些 JavaScript 解决方案为您提供自 1970 年 1 月 1 日午夜以来的毫秒数或秒数。

          IE 9+ 解决方案(IE 8 或更早版本不支持此功能。):

          var timestampInMilliseconds = Date.now();
          var timestampInSeconds = Date.now() / 1000; // A float value; not an integer.
              timestampInSeconds = Math.floor(Date.now() / 1000); // Floor it to get the seconds.
              timestampInSeconds = Date.now() / 1000 | 0; // Also you can do floor it like this.
              timestampInSeconds = Math.round(Date.now() / 1000); // Round it to get the seconds.
          

          获取更多关于Date.now()的信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now

          通用解决方案:

          // ‘+’ operator makes the operand numeric.
          // And ‘new’ operator can be used without the arguments ‘(……)’.
          var timestampInMilliseconds = +new Date;
          var timestampInSeconds = +new Date / 1000; // A float value; not an intger.
              timestampInSeconds = Math.floor(+new Date / 1000); // Floor it to get the seconds.
              timestampInSeconds = +new Date / 1000 | 0; // Also you can do floor it like this.
              timestampInSeconds = Math.round(+new Date / 1000); // Round it to get the seconds.
          

          如果您不想要这种情况,请小心使用。

          if(1000000 < Math.round(1000000.2)) // false.
          

          【讨论】:

          • 嗨,年轻的我。你好吗?
          【解决方案9】:
          Date.now()-Math.floor(Date.now()/1000/60/60/24)*24*60*60*1000
          

          这应该给你从一天开始的毫秒数。

          (Date.now()-Math.floor(Date.now()/1000/60/60/24)*24*60*60*1000)/1000
          

          这应该会给你几秒钟的时间。

          (Date.now()-(Date.now()/1000/60/60/24|0)*24*60*60*1000)/1000
          

          除了使用按位运算符来确定天数之外,其他与之前相同。

          【讨论】:

            【解决方案10】:

            自 1970 年 1 月 1 日以来,您可以找到另一种以秒/毫秒为单位获取时间的方法:

            var milliseconds = +new Date;        
            var seconds = milliseconds / 1000;
            

            但要小心这种方法,因为它可能难以阅读和理解。

            【讨论】:

            • 我不知道什么时候使用语言的副作用是一种更优雅的方式。
            【解决方案11】:

            更好的捷径:

            +new Date # Milliseconds since Linux epoch
            +new Date / 1000 # Seconds since Linux epoch
            Math.round(+new Date / 1000) #Seconds without decimals since Linux epoch
            

            【讨论】:

              【解决方案12】:

              在 2020 年的某一天,在 Chrome 80.0.3987.132 中,这将提供 1584533105

              ~~(new Date()/1000) // 1584533105
              Number.isInteger(~~(new Date()/1000)) // true
              

              【讨论】:

                【解决方案13】:

                获取今天的总秒数:

                getTodaysTotalSeconds(){
                    let date = new Date();        
                    return +(date.getHours() * 60 * 60) + (date.getMinutes() * 60) + date.getSeconds();
                }
                

                我添加了+ 作为回报,返回int。这可能对其他开发人员有所帮助。 :)

                【讨论】:

                  【解决方案14】:

                  如果您只需要在三个 JS 中使用几秒钟,请在函数中使用以下代码之一使用 window.requestAnimationFrame()

                  let sec = parseInt(Date.now().toString()[10]); console.log(' counting Seconds =&gt; '+ sec );

                  let currentTime= Date.now();

                  let secAsString= time.toString()[10];

                  let sec = parseInt(t);

                  console.log('counting Seconds =&gt;'+ sec );

                  【讨论】:

                  • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
                  猜你喜欢
                  • 1970-01-01
                  • 2023-03-18
                  • 2011-09-03
                  • 1970-01-01
                  • 2017-11-29
                  • 2012-01-15
                  • 1970-01-01
                  • 1970-01-01
                  • 2011-10-25
                  相关资源
                  最近更新 更多