【问题标题】:How to get current time with jQuery如何使用 jQuery 获取当前时间
【发布时间】:2013-12-25 17:47:19
【问题描述】:

以下以微秒为单位返回时间,例如 4565212462。

alert( $.now() );

如何将其转换为人类可读的时间格式,例如 (hours:minutes:seconds)

【问题讨论】:

  • $.now() 不需要 jQuery,因为 JavaScript 有一个原生实现:stackoverflow.com/questions/20456712/…
  • 更正:(1) 已替换为原生 Date.now(),以及 (2) 返回的时间以毫秒为单位,而不是微秒。

标签: jquery datetime time unix-timestamp microtime


【解决方案1】:

你可以这样尝试:

new Date($.now());

您也可以使用 Javascript:

var dt = new Date();
var time = dt.getHours() + ":" + dt.getMinutes() + ":" + dt.getSeconds();
document.write(time);

【讨论】:

  • 请注意 .getHours() 返回本地机器时区的小时数。如果用户的浏览器与您的时区不同,他们将从 getHours 获得其他结果。这也适用于 .toString() 方法。在 javascript 中控制时区很棘手(您必须计算您和所需时区之间的偏移量并相应地修改日期)。所以正如另一个答案中提到的,使用 moment.js 听起来是个好主意。 momentjs.com
  • 您还应该考虑在每个 get 中包含 padStart: dt.getMinutes().toString.padStart(2, '0') 这将确保数字保持 2 位长度并填充零,并且它遵循提议的 javascript 功能 - 非常适合未来:developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
  • @NegativeZero 一个非常有用(如果不是必要的话)的建议。不幸的是,它在 Firefox 上对我不起作用(我没有在其他浏览器上测试)。但是,将其重写为 String(dt.getMinutes()).padStart(2, '0') 对我有用。
  • moment.js 作为替代品有点过时(自己说),luxon 似乎是一个不错的当前替代品
  • @NegativeZero 必须是dt.getMinutes().toString().padStart(2, '0')toString()
【解决方案2】:

您需要手动获取所有“数字”

像这样:

var currentdate = new Date(); 
    var datetime = "Now: " + currentdate.getDate() + "/"
                + (currentdate.getMonth()+1)  + "/" 
                + currentdate.getFullYear() + " @ "  
                + currentdate.getHours() + ":"  
                + currentdate.getMinutes() + ":" 
                + currentdate.getSeconds();

document.write(datetime);

【讨论】:

    【解决方案3】:

    Date 对象转换为字符串,使用Date.prototype's conversion getters 之一,例如:

    var d = new Date();
    d+'';                  // "Sun Dec 08 2013 18:55:38 GMT+0100"
    d.toDateString();      // "Sun Dec 08 2013"
    d.toISOString();       // "2013-12-08T17:55:38.130Z"
    d.toLocaleDateString() // "8/12/2013" on my system
    d.toLocaleString()     // "8/12/2013 18.55.38" on my system
    d.toUTCString()        // "Sun, 08 Dec 2013 17:55:38 GMT"
    

    或者,如果您想要更多定制,请参阅the list of Date.prototype's getter methods

    【讨论】:

      【解决方案4】:

      你不需要为此使用 jQuery!

      native JavaScript implementation is Date.now()

      Date.now()$.now() 返回相同的值:

      Date.now(); // 1421715573651
      $.now();    // 1421715573651
      
      new Date(Date.now())   // Mon Jan 19 2015 20:02:55 GMT-0500 (Eastern Standard Time)
      new Date($.now());     // Mon Jan 19 2015 20:02:55 GMT-0500 (Eastern Standard Time)
      

      ..如果您希望时间格式为 hh-mm-ss:

      var now = new Date(Date.now());
      var formatted = now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds();
      // 20:10:58
      

      【讨论】:

      • 你不需要为 new Date() 提供参数,因为它默认为现在。
      • @Spode 啊,好点子。我不确定为什么其他答案都在使用 jQuery。
      【解决方案5】:

      .clock {
      width: 260px;
      margin: 0 auto;
      padding: 30px;
      color: #FFF;background:#333;
      }
      .clock ul {
      width: 250px;
      margin: 0 auto;
      padding: 0;
      list-style: none;
      text-align: center
      }
      
      .clock ul li {
      display: inline;
      font-size: 3em;
      text-align: center;
      font-family: "Arial", Helvetica, sans-serif;
      text-shadow: 0 2px 5px #55c6ff, 0 3px 6px #55c6ff, 0 4px 7px #55c6ff
      }
      #Date { 
      font-family: 'Arial', Helvetica, sans-serif;
      font-size: 26px;
      text-align: center;
      text-shadow: 0 2px 5px #55c6ff, 0 3px 6px #55c6ff;
      padding-bottom: 40px;
      }
      
      #point {
      position: relative;
      -moz-animation: mymove 1s ease infinite;
      -webkit-animation: mymove 1s ease infinite;
      padding-left: 10px;
      padding-right: 10px
      }
      
      /* Animasi Detik Kedap - Kedip */
      @-webkit-keyframes mymove 
      {
      0% {opacity:1.0; text-shadow:0 0 20px #00c6ff;}
      50% {opacity:0; text-shadow:none; }
      100% {opacity:1.0; text-shadow:0 0 20px #00c6ff; } 
      }
      
      @-moz-keyframes mymove 
      {
      0% {opacity:1.0; text-shadow:0 0 20px #00c6ff;}
      50% {opacity:0; text-shadow:none; }
      100% {opacity:1.0; text-shadow:0 0 20px #00c6ff; } 
      }
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
      <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
      <script type="text/javascript">
      $(document).ready(function() {
      // Making 2 variable month and day
      var monthNames = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]; 
      var dayNames= ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]
      
      // make single object
      var newDate = new Date();
      // make current time
      newDate.setDate(newDate.getDate());
      // setting date and time
      $('#Date').html(dayNames[newDate.getDay()] + " " + newDate.getDate() + ' ' + monthNames[newDate.getMonth()] + ' ' + newDate.getFullYear());
      
      setInterval( function() {
      // Create a newDate() object and extract the seconds of the current time on the visitor's
      var seconds = new Date().getSeconds();
      // Add a leading zero to seconds value
      $("#sec").html(( seconds < 10 ? "0" : "" ) + seconds);
      },1000);
      
      setInterval( function() {
      // Create a newDate() object and extract the minutes of the current time on the visitor's
      var minutes = new Date().getMinutes();
      // Add a leading zero to the minutes value
      $("#min").html(( minutes < 10 ? "0" : "" ) + minutes);
      },1000);
      
      setInterval( function() {
      // Create a newDate() object and extract the hours of the current time on the visitor's
      var hours = new Date().getHours();
      // Add a leading zero to the hours value
      $("#hours").html(( hours < 10 ? "0" : "" ) + hours);
      }, 1000); 
      });
      </script>
      <div class="clock">
      <div id="Date"></div>
      <ul>
      <li id="hours"></li>
      <li id="point">:</li>
      <li id="min"></li>
      <li id="point">:</li>
      <li id="sec"></li>
      </ul>
      </div>

      【讨论】:

        【解决方案6】:

        jQuery.now() 返回:数字

        说明:返回一个代表当前时间的数字。

        此方法不接受任何参数。

        $.now() 方法是表达式(new Date).getTime() 返回的数字的简写。

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

        使用 Javascript 很简单:

        var d = new Date();
        var time = d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
        console.log(time);
        

        【讨论】:

          【解决方案7】:

          jQuery 的 $.now() 是 new Date().getTime() 的别名,一个内部 Javascript 函数。

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

          这将返回自 1970 年以来经过的秒数,通常称为(不一定正确)为 Unix 时间、纪元或时间戳,具体取决于您所处的圈子。计算日期/时间之间的差异非常方便使用简单的数学。它没有任何 TimeZone 信息,始终为 UTC。

          http://en.wikipedia.org/wiki/Unix_time

          除了这个别名之外没有必要使用 jQuery,它对日期/时间操作几乎没有什么帮助。

          如果您正在寻找一种在文本中表示时间的快速而肮脏的方式,Javascript Date 对象有一个“toString”原型,它将返回一个 ISO 格式的日期时间。

          new Date().toString();
          //returns "Thu Apr 30 2015 14:37:36 GMT+0100 (BST)"
          

          不过,您很可能需要自定义格式。 Date 对象能够提取您的相关详细信息,以便您可以构建自己的字符串表示。

          https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

          var d = new Date(); //without params it defaults to "now"
          var t = d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
          //Will return 14:37:36
          

          但是,正如您所要求的 jQuery 解决方案 - 您可能正在使用旧版浏览器。如果您想做更具体的事情 - 尤其是将字符串解释为 Date 对象(对 API 响应很有用),您可能需要查看 Moment.js。

          http://momentjs.com/

          这将确保跨浏览器的兼容性并大大改进了格式,而无需将大量字符串连接在一起!例如:

          moment().format('hh:mm:ss');
          //Will return 14:37:36
          

          【讨论】:

            【解决方案8】:

            我使用moment 来满足我所有的时间操作/显示需求(客户端和node.js,如果你使用它),如果你只需要一个简单的格式,上面的答案就可以了,如果你正在寻找一些东西更复杂一点,时刻是 IMO 的路。

            【讨论】:

              【解决方案9】:
              <html>
              <head>
              <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
              </script>
              <script>
                  function ShowLocalDate()
                  {
                  var dNow = new Date();
                  var localdate= (dNow.getMonth()+1) + '/' + dNow.getDate() + '/' + dNow.getFullYear() + ' ' + dNow.getHours() + ':' + dNow.getMinutes();
                  $('#currentDate').text(localdate)
                  }
              </script>
              
              </head>
              <body>
                  enter code here
                  <h1>Get current local enter code here Date in JQuery</h1>
                  <label id="currentDate">This is current local Date Time in JQuery</p>
                  <button type="`enter code here button onclick="ShowLocalDate()">Show Local DateTime</button>
              
              </body>
              </html> 
              

              您可以从以下链接获取更多信息

              http://www.morgantechspace.com/2013/11/Get-current-Date-time-in-JQuery.html#GetLocalDateTimeinJQuery

              【讨论】:

                【解决方案10】:

                试试

                console.log(
                  new Date().toLocaleString().slice(9, -3)
                  , new Date().toString().slice(16, -15)
                );

                【讨论】:

                  【解决方案11】:

                  使用 JavaScript 原生日期函数,您可以根据需要获取 hoursminutesseconds。如果您希望以特定方式格式化日期和时间,您可能需要实现一个扩展 JavaScript Date 原型的方法。

                  这里已经实现了一个:https://github.com/jacwright/date.format

                  【讨论】:

                    【解决方案12】:

                    <p id="date"></p>
                    
                    <script>
                    var d = new Date();
                    document.getElementById("date").innerHTML = d.toTimeString();
                    </script>

                    你可以在 JS 中使用 Date()。

                    【讨论】:

                      【解决方案13】:

                      以下

                      function gettzdate(){
                          var fd = moment().format('YYYY-MM-DDTHH:MM:ss');
                          return fd ; 
                      }
                      

                      用于将当前日期强制为&lt;input type="datetime-local"&gt;

                      【讨论】:

                        【解决方案14】:

                        对于 SQL TIMESTAMP 的本地时间ISO8601,您可以尝试:

                        var tzoffset = (new Date()).getTimezoneOffset() * 60000;
                        var localISOTime = (new Date(Date.now() - tzoffset))
                          .toISOString()
                          .slice(0, 19)
                          .replace('T', ' ');
                        $('#mydatediv').val(localISOTime);
                        

                        【讨论】:

                          【解决方案15】:

                          console.log(
                            new Date().toLocaleString().slice(9, -3)
                            , new Date().toString().slice(16, -15)
                          );

                          【讨论】:

                          • 为你的答案添加相关解释
                          猜你喜欢
                          • 1970-01-01
                          • 2011-04-06
                          • 2011-04-05
                          • 2013-12-30
                          • 2013-07-27
                          • 1970-01-01
                          • 2011-02-16
                          • 1970-01-01
                          • 2021-01-28
                          相关资源
                          最近更新 更多