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

前端 未结 16 1377
野性不改
野性不改 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:08

    Here's a few variations that will work.

    const oneLiner = (hour = "00", min = "00", sec = "00") => `${(hour % 12) || 12}:${("0" + min).slice(-2)}:${sec} ${(hour < 12) ? 'am' : 'pm'}`
    console.log('oneliner', oneLiner(..."13:05:12".split(":")))
    
    
    
    const oneLinerWithObjectInput = ({hour = "00", min = "00", sec = "00"} = {}) => `${(hour % 12) || 12}:${("0" + min).slice(-2)}:${sec} ${(hour < 12) ? 'am' : 'pm'}`
    console.log('onelinerWithObjectInput', oneLinerWithObjectInput({
       hour: "13:05:12".split(":")[0],
       min: "13:05:12".split(":")[1],
       sec: "13:05:12".split(":")[2]
    }))
    
    
    const multiLineWithObjectInput = ({hour = "00", min = "00", sec = "00"} = {}) => {
       const newHour = (hour % 12) || 12
           , newMin  = ("0" + min).slice(-2)
           , ampm    = (hour < 12) ? 'am' : 'pm'
       return `${newHour}:${newMin}:${sec} ${ampm}`
    }
    console.log('multiLineWithObjectInput', multiLineWithObjectInput({
       hour: "13:05:12".split(":")[0],
       min: "13:05:12".split(":")[1],
       sec: "13:05:12".split(":")[2]
    }))

提交回复
热议问题