Dynamic date and time with moment.js and setInterval

后端 未结 4 1472
忘了有多久
忘了有多久 2021-02-07 12:22

I\'m trying to find out how I can display dynamic date and time using moment.js.

Apparently I can\'t figure out to use setInterval properly.

If possible I\'d pre

相关标签:
4条回答
  • 2021-02-07 12:31

    I've made a few modifications in your code:

    Note that the method update is now outside the ready event handler

    code:

    var datetime = null,
            date = null;
    
    var update = function () {
        date = moment(new Date())
        datetime.html(date.format('ffffdd, MMMM Do YYYY, h:mm:ss a'));
    };
    
    $(document).ready(function(){
        datetime = $('#datetime')
        update();
        setInterval(update, 1000);
    });
    

    working demo: jsfiddle

    0 讨论(0)
  • 2021-02-07 12:33

    Again, thanks for your answers. The code I ended up with follows. (Note danish i18n)

    moment.lang('da');
    
    var datetime = null, date = null;
    
    var datetime_update = function() {
      date = moment(new Date());
      datetime.html(date.format('[Lige nu: ] ffffdd [d.] Do MMMM YYYY [kl.] HH:mm:ss'));
    };
    
    $(document).ready(function() {
      datetime = $('#datetime');
      datetime_update();
      setInterval(datetime_update, 1000);
    });
    

    EDIT: Here nine months after I asked this quesiton I figured out this way to do it without jQuery (as I initially asked). Here it is:

    function date_time() {
      now = moment().format('ffffdd [d.] Do MMMM YYYY [kl.] HH:mm:ss');
      document.getElementById('timer').innerHTML = now;
      setTimeout(function () { date_time(); }, 1000);
    }
    date_time();
    

    And then of course use it with an HTML ID like:

    <span id="timer"></span>
    
    0 讨论(0)
  • 2021-02-07 12:34

    This is how it goes by me and its working u can check it here

    HTML
    

    < asp:Label ID="Label1" runat="server" Text='' >

    JavaScript
    < script language="javascript" type="text/javascript">
    function date_time() 
    {
    var dt = new Date();
    document.getElementById('<%=Label1.ClientID%>').innerHTML = dt;
    setTimeout(function () { date_time(); }, 1000);
    }
    date_time();
    < /script>
    
    0 讨论(0)
  • 2021-02-07 12:56

    Put

    date = moment(new Date());
    

    inside the update function. Now you're just printing the same date every second ;)

    0 讨论(0)
提交回复
热议问题