简体   繁体   中英

Javascript 24hours to 12hours

How could I change the time from a 24hr clock to a 12hour in javascript? I also want it to say AM and PM but I don't know-how. I'm a starter in JS.

var tmonth = new Array(
  "January",
  "February",
  "March",
  "April",
  "May",
  "June",
  "July",
  "August",
  "September",
  "October",
  "November",
  "December"
);

function GetClock() {
  var d = new Date();
  var nday = d.getDay(),
    nmonth = d.getMonth(),
    ndate = d.getDate();
  var nhour = d.getHours(),
    nmin = d.getMinutes(),
    nsec = d.getSeconds();
  if (nmin <= 9) nmin = "0" + nmin;
  if (nsec <= 9) nsec = "0" + nsec;

  document.getElementById("date").innerHTML =
    "" + tday[nday] + ", " + tmonth[nmonth] + " " + ndate + "";
  document.getElementById("time").innerHTML =
    " " + nhour + ":" + nmin + ":" + nsec + "";
}

window.onload = function () {
  GetClock();
  setInterval(GetClock, 1000);
};

You could simplify this quite a bit by not declaring unnecessary variables and using template literals .

(hours % 12) || 12 (hours % 12) || 12 will give you the hours.

`${h >= 12? 'P': 'A'}M` `${h >= 12? 'P': 'A'}M` will give you AM or PM

% is modulus

|| is a logical OR

condition? true: false condition? true: false is a ternary

Also, .padStart()

function GetClock() {
  let d = new Date(),
      h = d.getHours();

  document.getElementById("date").innerHTML =
    `${tday[d.getDay()]}, ${tmonth[d.getMonth()]} ${d.getDate()}`;

  document.getElementById("time").innerHTML =
    `${(h % 12) || 12}:${d.getMinutes().padStart(2, '0')}:${d.getSeconds().padStart(2, '0')} ${h >= 12 ? 'P' : 'A'}M`;
}

That being said, the 24 hour timestamp really is superior in that it naturally, explicitly states what time it is. There's no is that morning or night?

(new Date()).toTimeString().substr(0,8) , boom, timestamp done.

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