-1

I am trying to build a digital clock with HTML, CSS and JavaScript. I made a buttun that will toggle between 12hr and 24hr system. I am stuck with the logic on how to make that possible.

function displayTime(){
    let d = new Date()
    let hour = d.getHours()
    let minute = d.getMinutes()
    let second = d.getSeconds()
    let amOrPm = "AM"
    let clockSystem = document.getElementById("24hr-btn")

    // Indicates whether its AM or PM
    if (hour >= 12){
        amOrPm = "PM"
    }
   // Toggle Clock System
    function clockSystemTime(){
         // sets the clock to the 12hr system clock
        if (hour > 12) {
            hour -= 12
    } else {
        hour += 12
        }
    }

    if (hour < 0){
        hour = "0" + hour
    }

    if (minute < 10){
        minute = "0" + minute
    }

    if (second < 10){
        second = "0" + second
    }

    document.getElementById("clock").innerHTML = hour + ":" + minute + ":" + second + " " + amOrPm;
}

setInterval(displayTime, 1000)

your text

DevAldo
  • 3
  • 4

2 Answers2

2

It would be much simpler and less prone to error if you use the Intl API.

Reference

This provides a 12hour clock:

const date = new Date(Date.UTC(2020, 11, 20, 3, 23, 16, 738));
console.log(new Intl.DateTimeFormat('en-US', { timeStyle: 'short', hour12: false, }).format(date));

This provides a 24 hour clock:

const date = new Date(Date.UTC(2020, 11, 20, 3, 23, 16, 738));
console.log(new Intl.DateTimeFormat('en-US', { timeStyle: 'short', hour12: true, }).format(date));

Thus:

let twelveHour = false;

function displayTime(){
   const date = new Date();
   document.getElementById("clock").innerHTML = new Intl.DateTimeFormat('en-US', { timeStyle: 'long', hour12: twelveHour, }).format(date);
}
    

document.getElementById("clock").addEventListener("click", ()=>{
  clearInterval(interval);
  twelveHour = !twelveHour;
  var interval = setInterval(displayTime, 1000)    
})
<button id="clock">Click Me</button>
Randy Casburn
  • 13,840
  • 1
  • 16
  • 31
1

Perhaps you could find answers here? How do you display JavaScript datetime in 12 hour AM/PM format?

If not, then the logic would be as follows. Date returns a 24-hour date. Therefore, getting the hours would be the only issue we could face in converting time.

If the hour is greater than twelve, then subtract 12 from hours and set the clock to PM. If it's not, just grab the hours. Everything else like minutes and seconds should remain the same.

As to the button, just make it so that on a user click, it will change a JS variable containing whether you are doing 12 or 24 hour notation. If 12, run through the logic I described above. If 24, just take what the object gives you.

let d = new Date();
let system = 12;
let hours;

if (system == 12) {
  hours = d.getHours() > 12 ? d.getHours() - 12 : d.getHours();
} else if (system == 24) {
  hours = d.getHours();
}

function toggleTime() {
  // sets the system to 12 if it's set to 24, and vice versa
  system = system == 12 ? 24 : 12;

  if (system == 12) {
    hours = d.getHours() > 12 ? d.getHours() - 12 : d.getHours();
  } else if (system == 24) {
    hours = d.getHours();
  }
}


let timeEl = document.createElement('p');
document.body.append(timeEl);

let dateString = '';

function setDateString() {
  d = new Date();
  dateString = `${hours}:${d.getMinutes()}:${d.getSeconds()}`;
  timeEl.innerHTML = dateString;
}

setInterval(setDateString, 1000);
<button onclick="toggleTime()">Toggle</button>

It's a pretty small example, and it still has it's things to fix, but maybe it'll help.

Dominic R.
  • 53
  • 6
  • I get all that you said, i know how to set the clock to 12hrs by subtracting 12 hrs from the time. My problem now is how to make a button that will switch between the 12hr system and 24hr. I am fairly new to Javascript so please pardon my ignorance, I am still learning, – DevAldo Dec 20 '22 at 19:39
  • 1
    You're fine! Make a button in HTML and give it an onclick attribute of a function you'll create in JS. The function should just switch between the two times, and you should display the time based on what system the toggled variable says you should use. I'll put together an example in the original post. – Dominic R. Dec 21 '22 at 13:21