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
    Regular Coder
    Join Date
    May 2012
    Location
    France
    Posts
    224
    Thanks
    0
    Thanked 32 Times in 30 Posts

    Macintosh

    Converting from 24 hour clock to AM / PM
    0000 to 0059 add 12 hours to 0 => 12 hours
    0000 --> 12 midnight
    0015 --> 12:15 AM
    0030 --> 12:30 AM
    0059 --> 12:59 AM

    0100 to 1159 straight conversion to AM
    0100 --> 01:00 AM
    0300 --> 03:00 AM
    0700 --> 07:00 AM
    0830 --> 08:30 AM
    1000 --> 10:00 AM
    1159 --> 11:59 AM
    1200 to 1259 straight conversion to PM
    1200 --> 12 noon
    1215 --> 12:15 PM
    1230 --> 12:30 PM
    1259 --> 12:59 PM
    1300 to 2359 subtract 12 hours
    1300 --> 01:00 PM
    1500 --> 03:00 PM
    1800 --> 06:00 PM
    2030 --> 08:30 PM
    2215 --> 10:15 PM
    2359 --> 11:59 PM

    Then script could be
    Code:
    function startTime(){
       var today=new Date();
       var h=today.getHours();
       var m=today.getMinutes();
       // we compare numbers (and not strings)
       var s='AM';if (11<h) s='PM';
       if (h<1) h='12';
       if (12<h) h-=12;
       // add a zero in front of numbers<10
       h=checkTime(h);
       m=checkTime(m);
       var r=h+":"+m+" "+s;
       r=r.replace(/12:00 AM/,'12 midnight').replace(/12:00 PM/,'12 noon');
    
    document.getElementById('txt').innerHTML=r;
    t=setTimeout(startTime,500);// to indicate the function (a javascript object and not a string)
    }
    startTime();// to execute the function
    function checkTime(i){if (i<10) i="0"+i;return i;}
    Last edited by 007julien; 05-24-2012 at 11:05 PM.


  •  

    Posting Permissions

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