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
5 Réponses
+ 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
+ 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"));
+ 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>'
}
+ 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)
0
Thanks guys, I will try 👍