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

后端 未结 27 3082
慢半拍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:17

    It will return the following format like

    09:56 AM
    

    appending zero in start for the hours as well if it is less than 10

    Here it is using ES6 syntax

    const getTimeAMPMFormat = (date) => {
      let hours = date.getHours();
      let minutes = date.getMinutes();
      const ampm = hours >= 12 ? 'PM' : 'AM';
      hours = hours % 12;
      hours = hours ? hours : 12; // the hour '0' should be '12'
      hours = hours < 10 ? '0' + hours : hours;
      // appending zero in the start if hours less than 10
      minutes = minutes < 10 ? '0' + minutes : minutes;
      return hours + ':' + minutes + ' ' + ampm;
    };
    console.log(getTimeAMPMFormat(new Date)); // 09:59 AM

提交回复
热议问题