Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    Regular Coder
    Join Date
    Sep 2011
    Posts
    184
    Thanks
    140
    Thanked 0 Times in 0 Posts

    Javascript Clock h:mm TT format

    Hello,

    I need your help,

    How could the simple code below for a javascript be modified such that the clock will display in the format h:mm TT (ie. 4:52 PM) as opposed to its current setting right now of: hh:mm:ss?

    Code:
    <html>
    <head>
    <script type="text/javascript">
    function startTime()
    {
    var today=new Date();
    var h=today.getHours();
    var m=today.getMinutes();
    var s=today.getSeconds();
    // add a zero in front of numbers<10
    m=checkTime(m);
    s=checkTime(s);
    document.getElementById('txt').innerHTML=h+":"+m+":"+s;
    t=setTimeout('startTime()',500);
    }
    
    function checkTime(i)
    {
    if (i<10)
      {
      i="0" + i;
      }
    return i;
    }
    </script>
    Any help with this is greatly and much appreciated.

    Cheers,

    Jay

  • #2
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,438
    Thanks
    75
    Thanked 4,372 Times in 4,337 Posts
    Code:
    function startTime()
    {
        var today=new Date();
        var h=today.getHours();
        var m=today.getMinutes();
        if ( m < 10 ) m = "0" + m;
        var ampm = ( h >= 12 ) ? " PM" : " AM";
        if ( h > 12 ) h -= 12;
        if ( h == 0 ) h = 12;
    
        document.getElementById('txt').innerHTML = h + ":" + m + ampm;
        t=setTimeout(startTime,500);
    }
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •