I want to make a webpage that displays the current time. When the \"12-hour format\" button is clicked, the time in 12-hour time will display in the div area. When the \"24-hour
Since deadline at work is coming and right now is really just around the corner, I have decided to answer this 5 years old question.
Most people recommended using Moment.js library, which is really fine, because in most cases there is no point in reinventing the wheel and trusting a library with 9,897,199 weekly npm downloads is without any doubts a sane choice.
However, since the only answer providing solution based on OP's code seems to have some bugs in it; I would like to humbly propose my solution:
const FORMATS = {
TwelveHours: 12,
TwentyFourHours: 24
}
class Clock {
format = FORMATS.TwentyFourHours;
constructor(clockDivId) {
this.clockDivId = clockDivId;
this.clockInterval = setInterval(() => {
document.getElementById(clockDivId).innerHTML = this.getCurrentTime().format(this.format);
}, 500)
}
getCurrentTime() {
let today = new Date();
return new Time(today.getHours(), today.getMinutes(), today.getSeconds());
}
switchTo12HourFormat() {
this.format = FORMATS.TwelveHours
}
switchTo24HourFormat() {
this.format = FORMATS.TwentyFourHours
}
destroy() {
clearInterval(this.clockInterval);
}
}
class Time {
constructor(hours, minutes, seconds) {
this.hours = hours;
this.minutes = minutes;
this.seconds = seconds;
}
format(type) {
switch (type) {
case FORMATS.TwentyFourHours: {
return this.print(this.hours)
}
case FORMATS.TwelveHours: {
let tag = this.hours >= 12 ? 'p.m' : 'a.m';
let hours = this.hours % 12;
if (hours == 0) {
hours = 12;
}
return this.print(hours) + ' ' + tag;
}
}
}
//private
to2Digits(number) {
return number < 10 ? '0' + number : '' + number;
}
print(hours) {
return this.to2Digits(hours) + ':' + this.to2Digits(this.minutes) + ':' + this.to2Digits(this.seconds);
}
}
let clock = new Clock("clock");
<html>
<head>
<title>Clock</title>
</head>
<body>
<div id="clock"></div>
<br/>
<button onclick="clock.switchTo12HourFormat()">12 Hour Format</button>
<button onclick="clock.switchTo24HourFormat();">24 Hour Format</button>
</body>
</html>
Oh no, oh forking no! I have written "print" instead of "this.print" and I've run it in Google Chrome.
Basically UI got blocked by print dialog and I've lost all the code and had to write it again and now I am going home to enjoy some sleep and maybe, maybe one episode of HIMYM.
The 12 hour format can be obtained by using moment js a good library for performing time & date operations.
moment().format('YYYY-MM-DD, hh:mm:ss A')
where Post or ante meridiem (Note the only one of the character a p are also considered valid)
Link for Moment Js :-
https://momentjs.com
Agreed with others, yes issues with that code but for time conversion part - maybe you could do something simple like this using JavaScript built-in functions :
For 12-hr Format :
let formattedTime = new Date().toLocaleTimeString('en-US');
console.log(formattedTime)
For 24-hr Format :
let currentDateTime = new Date();
let formattedTime = currentDateTime.getHours() + ":" + currentDateTime.getMinutes() +":" + currentDateTime.getSeconds();
console.log(formattedTime)
Why dont you just use a library like Moment.js to do this for you.
http://momentjs.com/docs/
H, HH 24 hour time
h, or hh 12 hour time (use in conjunction with a or A)
so just use this code in JavaScript when using moment.js
the moment() method returns the current date in your specific format. So when you the user clicks the button you can call the following method on each button
moment().format("YYYY-MM-DD HH:mm"); // 24H clock
moment().format("YYYY-MM-DD hh:mm"); // 12H clock
Havn't tested this , but it should work
To be perfectly honest, I'm not entirely sure how you were trying to make this happen, but I think I understand what you wanted to have happen.
Give this a try:
window.onload = function() {
var h, m, s;
document.getElementById('twelveHrs').style.display = 'none';
document.getElementById('twentyFourHrs').style.display = 'none';
getTwelveHrs();
getTwentyFourHrs();
function getTwelveHrs() {
var tag = 'AM';
checkTime();
if(h > 12) {
h -= 12
tag = 'PM';
}
document.getElementById('twelveHrs').innerHTML = h + ':' + m + ':' + s + ' ' + tag;
t = setTimeout(function() {
getTwelveHrs()
}, 1000);
}
function getTwentyFourHrs() {
checkTime();
document.getElementById('twentyFourHrs').innerHTML = h + ':' + m + ':' + s;
var t = setTimeout(function() {
getTwentyFourHrs()
}, 1000);
}
function checkTime() {
var today = new Date();
h = today.getHours();
m = today.getMinutes();
s = today.getSeconds();
if(h < 10)
h = '0' + h;
if(m < 10)
m = '0' + m;
if(s < 10)
s = '0' + s;
return h, m, s;
}
}
function displayTwelveHrs() {
document.getElementById('twentyFourHrs').style.display = 'none';
document.getElementById('twelveHrs').style.display = '';
}
function displayTwentyFourHrs() {
document.getElementById('twelveHrs').style.display = 'none';
document.getElementById('twentyFourHrs').style.display = '';
}
Then replace your HTML with:
<div id="twelveHrs"></div>
<div id="twentyFourHrs"></div>
<br />
<button type="radio" onclick="displayTwelveHrs()">12 Hour Format</button>
<button type="radio" onclick="displayTwentyFourHrs()">24 Hour Format</button>
Basically, when the page loads, it'll start the clocks and hide the corresponding div
tags. Then you click a button, it will then display the div
you want while hiding the other.
A working JSFiddle can be found at: http://jsfiddle.net/fp3Luwzc/