Click here to Skip to main content
15,886,026 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
I have this code which shows a clock on a website. It displays like this
HTML
3:00:56 PM

However; the AM PM part doesn't show correctly. It's always PM. Any helpis appreciated.
JavaScript
function start() {
 var time = new Date()
 var hours = time.getHours() 
 hours = ((hours > 12) ? hours - 12 :(hours == 0) ? 12 :hours)

 var minutes = time.getMinutes()
 minutes=((minutes < 10) ? "0" : "" ) + minutes
 
 var seconds = time.getSeconds()
 seconds=((seconds < 10) ? "0" : "") + seconds

 var clock = hours + ":" + minutes + ":" + seconds + ((hours >= 12) ? " PM" : " AM"); 
 document.forms[0].display.value = clock

 timer = setTimeout("start()",1000)
}
Posted
Updated 13-Oct-12 9:26am
v2

Quote:
hours = ((hours > 12) ? hours - 12 :(hours == 0) ? 12 :hours)

Here you're discarding the PM/AM info.

A simple fix would be using another variable, that is:
JavaScript
function start() {
 
 var time = new Date()
 
 var hours24 = time.getHours()
 
 var hours = ((hours24 > 12) ? hours24 - 12 :(hours24 == 0) ? 12 :hours24)
 
 var minutes = time.getMinutes()
 
 minutes=((minutes < 10) ? "0" : "" ) + minutes
 
 var seconds = time.getSeconds()
 
 seconds=((seconds < 10) ? "0" : "") + seconds
 
 var clock = hours + ":" + minutes + ":" + seconds + ((hours24 >= 12) ? " PM" : " AM");
 
 document.forms[0].display.value = clock
 
 timer = setTimeout("start()",1000)
 
}
 
Share this answer
 
Comments
Member 7766180 13-Oct-12 15:39pm    
Thank you. I now see what I did wrong. I appreciate the help.
CPallini 13-Oct-12 15:51pm    
You are welcome.
Monjurul Habib 15-Oct-12 16:41pm    
5!
Hi,

Here is a solution called "High Resolution Digital Clock" that has been around for pretty long time; it shows date/time and is easily customizable. You can see full-working: DEMO[^] - refer to the page footer.

Following is a Javascript file that does the job (note: in body section of the page you have to create a div element and set its ID corresponding to the variable:
var _tClock = "Clk"


Listing 1. High-Resolution Digital Clock (shows Date/Time)
C#
//******************************************************************************
// Module           :   DigitalClock.js
// Author           :   Alexander Bell
// Description      :   High-Resolution Digital Clock (ASP.NET/Javascript)

//******************************************************************************
// DISCLAIMER: This Application is provide on AS IS basis without any warranty
//******************************************************************************

// div element ID to display Date/Time
var _tClock = "Clk";

// var to start/stop clock updates
var _pID="";

// start clock onload
StartTopClockOnLoad(StartTopClock);

// loader
function StartTopClockOnLoad(tFunc)
{
    if (window.addEventListener)
    { window.addEventListener('load', tFunc, false);}
    else if (window.attachEvent) {window.attachEvent('onload', tFunc); }
}

// start digital clock
function StartTopClock()
{ _pID = window.setInterval('UpdateTopClock()', 100);}

// update date/time reading
function UpdateTopClock()
{
    try
    {
        (document.getElementById(_tClock)).innerHTML =
         DateAndTime('d', 't', '', '', '', '');
    }
    catch (e) { }
}

// function to return date/time string
//****************************************************************
// ShowDate :   Flag to include DATE
// ShowTime :   Flag to include TIME
// md       :   Day/Month format: MM/DD (default) or DD/MM
// Clock24  :   Use 12 or 24 hr. Clock
// ShowMS   :   Flag to include milliseconds (1 digit)
// LocUTC   :   Select between Local (default) or UTC time
function DateAndTime(ShowDate,
                     ShowTime,
                     md,
                     Clock24,
                     ShowMS,
                     LocUTC)
{
    // private vars
    var yyyy;       // Year
    var mm;         // Month
    var dd;         // Day
    var h;          // Hours
    var m;          // Minutes
    var s;          // Seconds
    var ms;         // Milliseconds
    var ampm;       // AM or PM
    var strD;       // temp string for Date
    var strT;       // temp string for Time
    var ret="";     // return string

    // new DATE and TIME object
    dtNow = new Date();

    // if parameter not empty, format and add date
    if (ShowDate!=""){
        // UTC DATE
        if (LocUTC=="UTC") {
            yyyy =dtNow.getUTCFullYear();
            mm =dtNow.getUTCMonth()+1;
            dd =dtNow.getUTCDate();
        }
        // local DATE(Default)
        else {
            yyyy =dtNow.getFullYear();
            //yyyy =dtNow.getYear();
            mm =dtNow.getMonth()+1;
            dd =dtNow.getDate();
        }

        // use 2 digits MM/DD format
        if (mm<10) mm="0"+mm;
        if (dd<10) dd="0"+dd;

        // use MMDD or DDMM (Default: MMDD)
        if (md=="ddmm") {strD= dd + '/' + mm + '/' + yyyy;}
        else {strD= mm + '/'+ dd +'/' + yyyy;}

        //DATE STRING
        ret=strD + " ";
    }

    // if parameter not empty, format and add time
    if (ShowTime != "")
    {
        // UTC time
        if (LocUTC=="UTC") {
            h =dtNow.getUTCHours();
            m =dtNow.getUTCMinutes();
            s =dtNow.getUTCSeconds();
            ms=dtNow.getUTCMilliseconds();
        }
        // local time(Default)
        else {
            h =dtNow.getHours();
            m =dtNow.getMinutes();
            s =dtNow.getSeconds();
            ms=dtNow.getMilliseconds();
        }
        // use 2 digits for H, M and S
        if (h<10) h="0"+h;
        if (m<10) m="0"+m;
        if (s<10) s="0"+s;

        // add milliseconds
        if (ShowMS != "") { ms = "." + Math.round(ms / 100 - 0.5); } else {ms = ""; }

        // use 12/24 Clock (default 12 hr clock)
        if (Clock24=="24") {strT =h+':'+m+':'+s + ms;}
        else {
            ampm= (h>=12) ? "PM":"AM";
            if (h>12)   h-=12;
            if (h==0)   h=12;
            strT= h + ':' + m + ':' + s + ms + ' ' + ampm;
         }
        // time string
        ret += strT;
    }

    // optional UTC prefix
    ret=((LocUTC=="UTC")? "UTC " : "" ) + ret;

    // return string
    return(ret);
}


Pertinent to this case I would recommend to use setInterval() instead of setTimeout(), which require recursion.

Solution can be easily integrated into either HTML, or ASP.NET files. It can be customized for higher resolution, etc. using the flag vars.
Kind regards,
AB
 
Share this answer
 
Comments
Member 7766180 14-Oct-12 11:00am    
Thank you for your help. I appreciate it.
DrABELL 14-Oct-12 11:20am    
You are welcome! Good luck with your project.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900