본문 바로가기

Develop/HTML & JavaScript & CSS

12 시간 AM/PM 형식으로 표현

var d = new Date('1999-12-31 13:46');

 

// returns date object in 12hr (AM/PM) format
function formatAMPM(date) {
var yyyyMMdd = date.getFullYear()+ '. ' + (date.getMonth()+1)+ '. ' + date.getDate();
var hours = date.getHours();
var minutes = date.getMinutes();
return yyyyMMdd + ' ' + (hours < 12 ? 'A' : 'P') + 'M' + ' ' + (hours % 12 || 12) + ':' + minutes.toString().padStart(2, '0');
}

 

formatAMPM(d);

 

result : 1999. 12. 31 PM 1:46