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

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

    Updated for more compression

    const formatAMPM = (date) => {
      let hours = date.getHours();
      let minutes = date.getMinutes();    
      const ampm = hours >= 12 ? 'pm' : 'am';
    
      hours %= 12;
      hours = hours || 12;    
      minutes = minutes < 10 ? `0${minutes}` : minutes;
    
      const strTime = `${hours}:${minutes} ${ampm}`;
    
      return strTime;
    };
    
    console.log(formatAMPM(new Date()));
    

提交回复
热议问题