[removed] convert 24-hour time-of-day string to 12-hour time with AM/PM and no timezone

前端 未结 16 1388
野性不改
野性不改 2020-11-30 03:35

The server is sending a string in this format: 18:00:00. This is a time-of-day value independent of any date. How to convert it to 6:00PM in Javasc

16条回答
  •  清歌不尽
    2020-11-30 04:17

    Here's my way using if statements.

    const converTime = (time) => {
      let hour = (time.split(':'))[0]
      let min = (time.split(':'))[1]
      let part = hour > 12 ? 'pm' : 'am';
      
      min = (min+'').length == 1 ? `0${min}` : min;
      hour = hour > 12 ? hour - 12 : hour;
      hour = (hour+'').length == 1 ? `0${hour}` : hour;
    
      return (`${hour}:${min} ${part}`)
    }
    
    console.log(converTime('18:00:00'))
    console.log(converTime('6:5:00'))

提交回复
热议问题