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

前端 未结 16 1372
野性不改
野性不改 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条回答
  •  -上瘾入骨i
    2020-11-30 04:15

    toLocaleTimeString() makes this very simple. There is no need to do this yourself anymore. You'll be happier and live longer if you don't attack dates with string methods.

    const timeString = '18:00:00'
    // Append any date. Use your birthday.
    const timeString12hr = new Date('1970-01-01T' + timeString + 'Z')
      .toLocaleTimeString({},
        {timeZone:'UTC',hour12:true,hour:'numeric',minute:'numeric'}
      );
    document.getElementById('myTime').innerText = timeString12hr

提交回复
热议问题