简体   繁体   中英

I am trying to convert to a 12 hour format in javascript, but when I use the modulo operator it changes PM back to AM

I can change the time from military time to 12-hour format, but when I use the modulo operator it also changes the time from PM to AM. How do I change to the current time in 12-hour format without altering AM/PM?

 var now = new Date() var h = now.getHours(); h = h % 12; var m = now.getMinutes(); var s = now.getSeconds(); document.getElementById("hours").innerHTML = h; document.getElementById("minutes").innerHTML = m; document.getElementById("seconds").innerHTML = s; var suffix = "AM"; //set to PM if needed if (h >= 12) { suffix = "PM"; h = h - 12; } //take care of midnight if (h === 0) { h = 12; } document.getElementById("ampm").innerHTML = suffix; 
 <body> <main> <h1>Digital clock</h1> <fieldset> <legend>Clock</legend> <span id="hours">&nbsp;</span>: <span id="minutes">&nbsp;</span>: <span id="seconds">&nbsp;</span>&nbsp; <span id="ampm">&nbsp;</span> </fieldset> </main> </body> 

You change the hours h before using them. The test h >= 12 will always be false , because h = h % 12; happens before.

Use the modulo operator after:

var suffix = h < 12? "AM": "PM";   // test must be performed on the unaltered h (between 0 and 23)

h = h % 12;                        // use modulo after testing "h >= 12"

if (h === 0) {
    h = 12;
}

// alter DOM textContent here

BTW, instead of using the modulo operator then check equality with 0 , you could do both in one statement, like this:

h = (h < 12? h : h - 12) + 1;       // if h is greater or equal to 12, substract 12 from it, if not then keep it the same. Then add 1

Depending on where you are in the world, you may just be able to get the time format with .toLocaleTimeString() :

 var timeEl = document.getElementById("time"); function getTime(){ timeEl.textContent = new Date().toLocaleTimeString(); setTimeout(getTime, 20); // Call the function again in 20ms } getTime(); // Initiate the clock 
 <h1>Digital clock</h1> <fieldset> <legend>Clock</legend> <span id="time"></span> </fieldset> 

But, if you were to need/want to write this out "long-hand", modulo isn't really needed. This is a straight-forward operation.

  • Get the current time.
  • Extract the hours.
  • If hours >= 12, subtract 12 (and set AM/PM to PM)
  • Correct the minutes and seconds for single digit answers.
  • Use .textContent to populate elements, not .innerHTML .

If you want an actual ticking clock, you'll need a timer to keep running the code over and over:

 var hEl = document.getElementById("hours"); var mEl = document.getElementById("minutes"); var sEl = document.getElementById("seconds"); var amPM = document.getElementById("ampm"); function fixDigit(val){ // turn a single digit into one with a "0" prepended to it return val.toString().length === 1 ? "0" + val : val; } function getTime(){ var time = new Date(); var h = time.getHours(); hEl.textContent = (h >= 12) ? h - 12: h; mEl.textContent = fixDigit(time.getMinutes()); sEl.textContent = fixDigit(time.getSeconds()); amPM.textContent = h < 12 ? "AM" : "PM"; setTimeout(getTime, 20); // Call the function again in 20ms } getTime(); // Initiate the clock 
 <h1>Digital clock</h1> <fieldset> <legend>Clock</legend> <span id="hours"></span>: <span id="minutes"></span>: <span id="seconds"></span> <span id="ampm"></span> </fieldset> 

The other answers are fine, but if you're looking for a pure math solution, that doesn't depend on "if" conditions, then consider this. I'll give an explanation in words first. Then follow that with a table since the words may not make a lot of sense without examples.

A modulo operator will always return a sequence of sequential integers starting from 0 . Since you want your answer to start from 1 , you will need to add 1 to the result of the modulo operation. But to keep your answer from being 1 too high, you need to subtract 1 from the input to the modulo operation. Finally, to avoid negative numbers, you can add 11 which, in modulo 12, will "wrap around" your answer 1 less than a complete cycle, which does the same thing as subtracting 1.

Confused? See the table below. The left-most column is your 24-hour clock input, and the right-most column is the output you want.

24      
Hr       Add   Modulo   (Modulo
Clock    11      12     12) + 1
=================================
0        11      11       12
1        12       0        1      
2        13       1        2
3        14       2        3
4        15       3        4
...
10       21       9       10
11       22      10       11
12       23      11       12
13       24       0        1     
14       25       1        2
15       26       2        3
...
22       33       9       10
23       34      10       11

So the final formula you may want to try is:

h12 = ((h24 + 11) % 12) + 1

Of course, you'll still need an if statement to check for the AM/PM indicator. But I got the sense that you were looking for a modulo-related answer (since this intuitively seems like the thing that should be possible using modulo and since you could do the entire translation using if statements if you wanted to.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM