Display 12-hour and 24-hour time - javascript

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 format" button is clicked, the time will show in 24-hour time in the div area. Currently nothing happens when these buttons are clicked. Help!
HTML:
<html>
<head>
<title>Clock</title>
<script type="text/javascript" src="clock.js"></script>
</head>
<body>
<div id="textbox"></div>
<br/>
<button type="radio" onclick="getTwelveHrs()">12 Hour Format</button>
<button type="radio" onclick="getTwentyFourHrs()">24 Hour Format</button>
</body>
</html>
JavaScript:
function getTwelveHours{
if (i < 10) {
i = "0" + i;
}
return i;
}
function startTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('textbox').innerHTML = h + ":" + m + ":" + s;
t = setTimeout(function () {
startTime()
}, 500);
}
startTime();
function getTwentyFourHrs() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('textbox').innerHTML = h + ":" + m + ":" + s;
var t = setTimeout(function() {
startTime()
}, 500);
}
function checkTime(i) {
if (i < 10) {
i = "0" + i
};
return i;
}

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

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)

const time = new Date().getHours('en-US',{hour12:false});
const time = new Date().getHours('en-US',{hour12:true});

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/

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.

Related

how can i print a sentences in a choosen time [duplicate]

This question already has answers here:
Fire event at a certain time of the day
(4 answers)
Closed 11 months ago.
im a noob in js xd, i want to put a text in an html in a choosen time of a clock!
i want it to print "make a wish" when its 11:11
the code:
function startTime() {
const today = new Date();
let h = today.getHours();
let m = today.getMinutes();
let s = today.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('txt').innerHTML = h + ":" + m + ":" + s;
setTimeout(startTime, 1000);
}
function checkTime(i) {
if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
This can be done via setInterval in javascript with some basic if condition checks.
First create a date object via new Date() then get hours and minutes, check if the hour and minute is equal to your specified time then print the value.
We need to set an interval of 60 seconds which is equal to 60,000 milliseconds to not print again the same value in that minute.
You can try this -
setInterval(function(){
var date = new Date();
if(date.getHours() === 11 && date.getMinutes() === 11){
console.log("make a wish");
}
}, 60000);
Something like this will do.
function startTime() {
const today = new Date();
let h = today.getHours();
let m = today.getMinutes();
let s = today.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('txt').innerHTML = h + ":" + m + ":" + s;
if (h == 11 && m == 11) {
console.log("Make a wish");
} else {
setTimeout(startTime, 1000);
}
}
function checkTime(i) {
if (i < 10) { i = "0" + i }; // add zero in front of numbers < 10
return i;
}
startTime();
<p id="txt"></p>
Use the callback function from SetInterval and get currentt time. afterwards you can check if it 11:11. If successful dont forget to clear the intervall.
const innterval = setInterval(function () {
check()
}, 5000);
function check() {
var today = new Date();
var t1111 = today.getHours() + ':' + today.getMinutes();
if (t1111 === '11:11') {
alert('11:11')
document.getElementById('txt').innerHTML = t111 + ' PARTY!'
clearInterval(innterval);
}
console.log('Current time: ' + t1111 + ' still Waiting')
}
<div id="txt"></div>

Javascript when live time strikes 23:00

I have be attempting this for quite a while now and cant get my head around it. I have a javascript which displays a live time. What i am trying to do is build an if statement that says if it hits 23:00:00 then open a link. can anyone help please? anything i use just blanks out the time :(
<script>
function startTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('txt').innerHTML = h + ":" + m + ":" + s;
var t = setTimeout(startTime, 500);
}
function checkTime(i) {
if (i < 10) {i = "0" + i};
return i;
}
</script>
</head>
<body onload="startTime()">
<div id="txt"></div>
You already calculate the time, just check to see if it's the time you want, and open a url.
function startTime() {
var today = new Date('Thu Jul 26 2018 23:00:00 GMT-0700 (Pacific Daylight Time)')
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
if (h === 23 && m === 0 && s === 0) {
window.open('https://www.stackoverflow.com', '_blank');
}
m = checkTime(m);
s = checkTime(s);
document.getElementById('txt').innerHTML = h + ":" + m + ":" + s;
var t = setTimeout(startTime, 500);
}
function checkTime(i) {
if (i < 10) {
i = "0" + i
};
return i;
}
<body onload="startTime()">
<div id="txt"></div>
</body>
A simple
...
document.getElementById('txt').innerHTML = h + ":" + m + ":" + s;
if (h == "23" && m == "00" && s == "00") {
alert("open link from here");
}
...
would do the trick.
Note:
You also have to check for s otherwise you'll open a new page every second.
refresh every second :
function timeLoop(){
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
var timeString = h+":"+m+":"+s
// print time
document.getElementById('txt').innerHTML = h + ":" + m + ":" + s;
// check timeString
if ( timeString === "23:00:00"){
// perform you actions here
}
}
document.body.onload = function(){
setInterval( timeLoop, 1000 );
}
What's happening here is
when body is loaded the timeLoop function starts looping every second, each loop updates the time displayed and checking it.
you can execute whatever code or function in side the if statement.
hope this helps
I think a simple setInterval() checking for the hour only would do it. The following code sets a interval checking the hour every 1 second. If the hour is 23 the interval is cleared to ensure that the triggered action runs only once and then does whatever you want to do. There is no need to check for minutes and seconds as well and this way you don't need to worry about leading zeros.
var interval = window.setInterval(function(){
var h = new Date().getHours();
if (h === 23) {
// clear interval to ensure that code runs only once
window.clearInterval(interval);
// do whatever you like
console.log(h);
}
},1000);

Javascript change time between military and AM/PM onclick

I have a Rails app where I'm displaying a realtime clock in my application layout. I'm using this code to make it work:
<div id="time" class="time_display"></div>
<script type="text/javascript">
function checkTime(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
function startTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
// add a zero in front of numbers<10
m = checkTime(m);
s = checkTime(s);
document.getElementById('time').innerHTML = h + ":" + m + ":" + s;
t = setTimeout(function () {
startTime()
}, 500);
}
startTime();
</script>
What I'd like to be able to do is somehow give the user the option to switch between a realtime clock in military time and regular AM/PM time with the AM/PM included but clicking on the div.
I've done some searching but haven't found anything that works too well. I'm open to any solutions someone might have be it JS or jQuery.
Any help would be greatly appreciated. If my question is not clear, please let me know.
Here is code. It get updated only on next tick, but you can manage to fix that if you want
function checkTime(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
function startTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
var ampm = h >= 12 ? 'pm' : 'am';
// add a zero in front of numbers<10
m = checkTime(m);
s = checkTime(s);
var timer = document.getElementById('time');
if (timer.type == 'r') {
h = h % 12;
h = h ? h : 12;
timer.innerHTML = h + ":" + m + ":" + s + " " + ampm;
} else
timer.innerHTML = h + ":" + m + ":" + s;
t = setTimeout(function () {
startTime()
}, 500);
document.getElementById('time').onclick = function () {
if (this.type == 'r')
this.type = 'm';
else
this.type = 'r';
}
}
startTime();
<div id="time" class="time_display"></div>
Really:
var ampm = 'am';
if(hours > 11){
ampm = 'pm';
if(hours > 12)hours = hours-12;
}
if(hours === 0)hours = 12;
Also, you could do something like:
today.toLocaleString().split(',')[1];

How to show current time in JavaScript in the format HH:MM:SS?

How do I show the current time in the format HH:MM:SS?
You can use native function Date.toLocaleTimeString():
var d = new Date();
var n = d.toLocaleTimeString();
This will display e.g.:
"11:33:01"
MDN: Date toLocaleTimeString
var d = new Date();
var n = d.toLocaleTimeString();
alert("The time is: \n"+n);
function checkTime(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
function startTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
// add a zero in front of numbers<10
m = checkTime(m);
s = checkTime(s);
document.getElementById('time').innerHTML = h + ":" + m + ":" + s;
t = setTimeout(function() {
startTime()
}, 500);
}
startTime();
<div id="time"></div>
DEMO using javaScript only
Update
Updated Demo
(function () {
function checkTime(i) {
return (i < 10) ? "0" + i : i;
}
function startTime() {
var today = new Date(),
h = checkTime(today.getHours()),
m = checkTime(today.getMinutes()),
s = checkTime(today.getSeconds());
document.getElementById('time').innerHTML = h + ":" + m + ":" + s;
t = setTimeout(function () {
startTime()
}, 500);
}
startTime();
})();
You can do this in Javascript.
var time = new Date();
console.log(time.getHours() + ":" + time.getMinutes() + ":" + time.getSeconds());
At present it returns 15:5:18. Note that if any of the values are less than 10, they will display using only one digit, not two.
Check this in JSFiddle
Updates:
For prefixed 0's try
var time = new Date();
console.log(
("0" + time.getHours()).slice(-2) + ":" +
("0" + time.getMinutes()).slice(-2) + ":" +
("0" + time.getSeconds()).slice(-2));
You can use moment.js to do this.
var now = new moment();
console.log(now.format("HH:mm:ss"));
Outputs:
16:30:03
new Date().toTimeString().slice(0,8)
Note that toLocaleTimeString() might return something like 9:00:00 AM.
Use this way:
var d = new Date();
localtime = d.toLocaleTimeString('en-US', { hour12: false });
Result: 18:56:31
function realtime() {
let time = moment().format('h:mm:ss a');
document.getElementById('time').innerHTML = time;
setInterval(() => {
time = moment().format('h:mm:ss a');
document.getElementById('time').innerHTML = time;
}, 1000)
}
realtime();
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.min.js"></script>
<div id="time"></div>
A very simple way using moment.js and setInterval.
setInterval(() => {
moment().format('h:mm:ss a');
}, 1000)
Sample output
Using setInterval() set to 1000ms or 1 second, the output will refresh every 1 second.
3:25:50 pm
This is how I use this method on one of my side projects.
setInterval(() => {
this.time = this.shared.time;
}, 1000)
Maybe you're wondering if using setInterval() would cause some performance issues.
Is setInterval CPU intensive?
I don't think setInterval is inherently going to cause you significant performance problems. I suspect the reputation may come from an earlier era, when CPUs were less powerful. ... - lonesomeday
No, setInterval is not CPU intensive in and of itself. If you have a lot of intervals running on very short cycles (or a very complex operation running on a moderately long interval), then that can easily become CPU intensive, depending upon exactly what your intervals are doing and how frequently they are doing it. ... - aroth
But in general, using setInterval really like a lot on your site may slow down things. 20 simultaneously running intervals with more or less heavy work will affect the show. And then again.. you really can mess up any part I guess that is not a problem of setInterval. ... - jAndy
new Date().toLocaleTimeString('it-IT')
The it-IT locale happens to pad the hour if needed and omits PM or AM 01:33:01
Compact clock function:
setInterval(function() {
let d = new Date()
console.log(`${d.getHours()}:${d.getMinutes()}:${d.getSeconds()}`)
}, 1000);
This code will output current time in HH:MM:SS format in console, it takes into account GMT timezones.
var currentTime = Date.now()
var GMT = -(new Date()).getTimezoneOffset()/60;
var totalSeconds = Math.floor(currentTime/1000);
seconds = ('0' + totalSeconds % 60).slice(-2);
var totalMinutes = Math.floor(totalSeconds/60);
minutes = ('0' + totalMinutes % 60).slice(-2);
var totalHours = Math.floor(totalMinutes/60);
hours = ('0' + (totalHours+GMT) % 24).slice(-2);
var timeDisplay = hours + ":" + minutes + ":" + seconds;
console.log(timeDisplay);
//Output is: 11:16:55
This is an example of how to set time in a div(only_time) using javascript.
function date_time() {
var date = new Date();
var am_pm = "AM";
var hour = date.getHours();
if(hour>=12){
am_pm = "PM";
}
if (hour == 0) {
hour = 12;
}
if(hour>12){
hour = hour - 12;
}
if(hour<10){
hour = "0"+hour;
}
var minute = date.getMinutes();
if (minute<10){
minute = "0"+minute;
}
var sec = date.getSeconds();
if(sec<10){
sec = "0"+sec;
}
document.getElementById("time").innerHTML = hour+":"+minute+":"+sec+" "+am_pm;
}
setInterval(date_time,500);
<per>
<div class="date" id="time"></div>
</per>
new Date().toLocaleTimeString()
function realtime() {
let time = moment().format('hh:mm:ss.SS a').replace("m", "");
document.getElementById('time').innerHTML = time;
setInterval(() => {
time = moment().format('hh:mm:ss.SS A');
document.getElementById('time').innerHTML = time;
}, 0)
}
realtime();
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.min.js"></script>
<div id="time"></div>
Use
Date.toLocaleTimeString()
// Depending on timezone, your results will vary
const event = new Date('August 19, 1975 23:15:30 GMT+00:00');
console.log(event.toLocaleTimeString('en-US'));
// expected output: 1:15:30 AM
console.log(event.toLocaleTimeString('it-IT'));
// expected output: 01:15:30
console.log(event.toLocaleTimeString('ar-EG'));
// expected output: ١٢:١٥:٣٠
Source

Javascript clock based on custom time

I am using the following script below, and what I am trying to do is to set a custom time to the script and for it to auto update without the need to re-set the time each time. (I only want to set the time once and want my script to keep track of the time and display it)
When I run the script it displays: NaN:NaN:NaN AM
My Code is as follows:
<div id="js_clock"> display clock here </div>
<script language="javascript">
function js_clock(clock_time)
{
var clock_hours = clock_time.getHours();
var clock_minutes = clock_time.getMinutes();
var clock_seconds = clock_time.getSeconds();
var clock_suffix = "AM";
if (clock_hours > 11){
clock_suffix = "PM";
clock_hours = clock_hours - 12;
}
if (clock_hours == 0){
clock_hours = 12;
}
if (clock_hours < 10){
clock_hours = "0" + clock_hours;
}
if (clock_minutes < 10){
clock_minutes = "0" + clock_minutes;
}
if (clock_seconds < 10){
clock_seconds = "0" + clock_seconds;
}
var clock_div = document.getElementById('js_clock');
clock_div.innerHTML = clock_hours + ":" + clock_minutes + ":" + clock_seconds + " " + clock_suffix;
setTimeout("js_clock()", 1000);
}
var serverTime = new Date("09:20:50");
js_clock(serverTime);
</script>
You have a problem creating the date, new Date("09:20:50"); returns Invalid Date.
if you want to set hours minutes and seconds use
new Date(year, month, day [, hour, minute, second, millisecond ])
or take a look here.
Also you forgot to pass a date to the setTimeout, try:
setTimeout(function() {
js_clock(new Date(/*pass hours minutes and seconds here*/))
}, 1000);
I think you've forgotten passing an argument to js_clock(). Maybe you shoud do:
setTimeout(
function() {
//Call the function again updating seconds by 1
js_clock(
new Date(
clock_time.getFullYear(),
clock_time.getMonth(),
clock_time.getDate(),
clock_time.getHours(),
clock_time.getMinutes(),
clock_time.getSeconds() + 1
)
);
},
1000
);
EDIT:
I missed the point this can be done with a single function call:
setTimeout(
function() {
js_clock(new Date(+clock_time + 1000));
},
1000
);
The +clock_time statement converts the Date object to milliseconds from the UNIX Epoch, so updating the time is as simple as summing 1000 milliseconds.
Thanks to user RobG ;-)
Your code has some serious flaws, such as the following.
setTimeout doesn't run at exactly the interval set, but as soon as it can afterward so this clock will slowly drift, sometimes by a lot.
Passing a string to Date and expecting it to be correctly parsed is problematic. In ECMA-262 ed 3 it was entirely implementation dependent, in ES5 the string is required to be a custom version of the ISO8601 long format (but note that not all browsers in use support ES5).
Lastly, if the client is busy, the function may not run for several seconds so the clock needs to be based on the client clock, then ajusted for the time difference.
The following function does all the above.
<script type="text/javascript">
var customClock = (function() {
var timeDiff;
var timeout;
function addZ(n) {
return (n < 10? '0' : '') + n;
}
function formatTime(d) {
return addZ(d.getHours()) + ':' +
addZ(d.getMinutes()) + ':' +
addZ(d.getSeconds());
}
return function (s) {
var now = new Date();
var then;
// Set lag to just after next full second
var lag = 1015 - now.getMilliseconds();
// Get the time difference if first run
if (s) {
s = s.split(':');
then = new Date(now);
then.setHours(+s[0], +s[1], +s[2], 0);
timeDiff = now - then;
}
now = new Date(now - timeDiff);
document.getElementById('clock').innerHTML = formatTime(now);
timeout = setTimeout(customClock, lag);
}
}());
window.onload = function() {
customClock('09:20:50');
}
</script>
<div id="clock"></div>
WAIT! just realised, this is still not showing the correct time. The error is gone, but the time isn't what you are looking for.
window.js_clock = function js_clock(clock_time) {
var clock_hours = clock_time.getHours();
var clock_minutes = clock_time.getMinutes();
var clock_seconds = clock_time.getSeconds();
var clock_suffix = "AM";
if (clock_hours > 11) {
clock_suffix = "PM";
clock_hours = clock_hours - 12;
}
if (clock_hours === 0) {
clock_hours = 12;
}
if (clock_hours < 10) {
clock_hours = "0" + clock_hours;
}
if (clock_minutes < 10) {
clock_minutes = "0" + clock_minutes;
}
if (clock_seconds < 10) {
clock_seconds = "0" + clock_seconds;
}
var clock_div = document.getElementById('js_clock');
clock_div.innerHTML = clock_hours + ":" + clock_minutes + ":" + clock_seconds + " " + clock_suffix;
setTimeout("js_clock(new Date())", 1000);
}
var serverTime = new Date("09:20:50");
window.js_clock(serverTime);​

Categories

Resources