一尘不染

如何以12小时AM / PM格式显示JavaScript日期时间?

javascript

您如何以12小时格式(AM / PM)显示JavaScript日期时间对象?


阅读 880

收藏
2020-04-25

共1个答案

一尘不染

function formatAMPM(date) {

  var hours = date.getHours();

  var minutes = date.getMinutes();

  var ampm = hours >= 12 ? 'pm' : 'am';

  hours = hours % 12;

  hours = hours ? hours : 12; // the hour '0' should be '12'

  minutes = minutes < 10 ? '0'+minutes : minutes;

  var strTime = hours + ':' + minutes + ' ' + ampm;

  return strTime;

}



console.log(formatAMPM(new Date));
2020-04-25