0

❝Is there any shortcut way to convert 24 hour format to 12 hour format (with am & pm) in JavaScript?❞

I already make a clock in 12 hour format (using "switch.....break" But, is there any shortcut way to convert 24 hour format to 12 hour format (with am & pm) in JavaScript? https://code.sololearn.com/Wyjs5qeY3x51/?ref=app

25th Aug 2021, 9:17 AM
Fꫀⲅძ᥆͟ᥙ᥉᯽
Fꫀⲅძ᥆͟ᥙ᥉᯽ - avatar
5 odpowiedzi
+ 4
const format = (H,M,S) => { return `${(H%12<10?'0':'')+H%12} : ${(M<10?'0':'')+M} : ${(S<10?'0':'')+S} ${H<12?'AM':'PM'}`} console.log(format(7,5,23)) console.log(format(11,35,10)) console.log(format(15,5,23)) console.log(format(23,35,3)) https://code.sololearn.com/W24pGFLUHb03/?ref=app
25th Aug 2021, 9:23 AM
SAN
SAN - avatar
+ 2
I created this function to do this: function formatDate(date) { var d = new Date(date); var hh = d.getHours(); var m = d.getMinutes(); var s = d.getSeconds(); var dd = "AM"; var h = hh; if (h >= 12) { h = hh - 12; dd = "PM"; } if (h == 0) { h = 12; } m = m < 10 ? "0" + m : m; s = s < 10 ? "0" + s : s; /* if you want 2 digit hours: h = h<10?"0"+h:h; */ var pattern = new RegExp("0?" + hh + ":" + m + ":" + s); var replacement = h + ":" + m; /* if you want to add seconds replacement += ":"+s; */ replacement += " " + dd; return date.replace(pattern, replacement); } alert(formatDate("February 04, 2011 12:00:00"));
26th Aug 2021, 2:46 AM
Arun Jamson
Arun Jamson - avatar
+ 1
Vadivelan I used this↓ if (hr>11){ sec=sec+'<span style="font-size: 6vw;"> PM</span>' } else { sec=sec+'<span style="font-size: 6vw;"> AM</span>' }
25th Aug 2021, 9:26 AM
Fꫀⲅძ᥆͟ᥙ᥉᯽
Fꫀⲅძ᥆͟ᥙ᥉᯽ - avatar
+ 1
yes there is https://code.sololearn.com/WTkSrXL2rb4d/?ref=app function addZero(x){ return x < 10 ? "0"+String(x) : String(x); } //24-Hour Format var date = new Date(); var hours = addZero(date.getHours()); var newformat = hours >= 12 ? 'PM' : 'AM'; // console.log(hours) var minutes = addZero(date.getMinutes()); //console.log(minutes) console.log(hours + ":" + minutes + ' ' +newformat) //12 hour format hours = hours % 12; hours = hours ? hours : 12; console.log(hours + ':' + minutes + ' ' + newformat)
25th Aug 2021, 9:34 AM
Pariket Thakur
Pariket Thakur - avatar
0
Thanks guys, I will try 👍
25th Aug 2021, 10:28 AM
Fꫀⲅძ᥆͟ᥙ᥉᯽
Fꫀⲅძ᥆͟ᥙ᥉᯽ - avatar