skip to Main Content

I’ve looked up different options to change the format but im not sure if im doing it right since none work.

Thank you in advance.

let hrs = document.getElementById(hours)
let min = document.getElementById(minute)
let sec = document.getElementById(second)


setInterval(()=>{
    
  let currenTime = new Date();
  

hours.innerHTML = (currenTime.getHours()<10?"0":"") + currenTime.getHours();

minute.innerHTML = (currenTime.getMinutes()<10?"0":"") + currenTime.
getMinutes();

second.innerHTML = (currenTime.getSeconds()<10?"0":"")+ currenTime.
getSeconds();
},1000)
 
if(hours == 0){
hours = 12;
}

3

Answers


  1. Use the hour12 option of the toLocaleTimeString() method.

    const d = new Date()
    console.log(d.toLocaleTimeString(undefined, { hour12: true }))
    Login or Signup to reply.
  2. let hrs = document.getElementById(hours)
    let min = document.getElementById(minute)
    let sec = document.getElementById(second)
    
    
    setInterval(()=>{
        
      let currenTime = new Date();
      let Hours= currenTime.getHours()
      if(Hours>12){
        Hours=Hours-12
       }
       if(Hours<10){
       Hours="0"+Hours
       }
    hours.innerHTML = Hours;
    
    minute.innerHTML = (currenTime.getMinutes()<10?"0":"") + currenTime.
    getMinutes();
    
    second.innerHTML = (currenTime.getSeconds()<10?"0":"")+ currenTime.
    getSeconds();
    },1000)
     
    if(hours == 0){
    hours = 12;
    }
    Login or Signup to reply.
  3. let hours = document.getElementById("hours");
    let minute = document.getElementById("minute");
    let second = document.getElementById("second");
    
    setInterval(() => {
        let currentTime = new Date();
        let Hours = currentTime.getHours();
    
        // Convert to 12-hour format
        if (Hours > 12) {
            Hours = Hours - 12;
        }
        // Add leading zero if less than 10
        if (Hours < 10) {
            Hours = "0" + Hours;
        }
    
        let Minutes = (currentTime.getMinutes() < 10 ? "0" : "") + currentTime.getMinutes();
        let Seconds = (currentTime.getSeconds() < 10 ? "0" : "") + currentTime.getSeconds();
    
        hours.innerHTML = Hours;
        minute.innerHTML = Minutes;
        second.innerHTML = Seconds;
    }, 1000);
    
    // Fix the incomplete if statement
    if (hours.innerHTML == "00") {
        hours.innerHTML = "12";
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search