How do you display JavaScript datetime in 12 hour AM/PM format?

后端 未结 27 3098
慢半拍i
慢半拍i 2020-11-22 02:36

How do you display a JavaScript datetime object in the 12 hour format (AM/PM)?

27条回答
  •  时光说笑
    2020-11-22 03:23

    function getDateTime() {
      var now = new Date();
      var year = now.getFullYear();
      var month = now.getMonth() + 1;
      var day = now.getDate();
    
      if (month.toString().length == 1) {
        month = '0' + month;
      }
      if (day.toString().length == 1) {
        day = '0' + day;
      }
    
      var hours = now.getHours();
      var minutes = now.getMinutes();
      var ampm = hours >= 12 ? 'pm' : 'am';
      hours = hours % 12;
      hours = hours ? hours : 12;
      minutes = minutes < 10 ? '0' + minutes : minutes;
      var timewithampm = hours + ':' + minutes + ' ' + ampm;
    
      var dateTime = monthNames[parseInt(month) - 1] + ' ' + day + ' ' + year + ' ' + timewithampm;
      return dateTime;
    }
    

提交回复
热议问题