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

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

    Short ES6 code

    const convertFrom24To12Format = (time24) => {
      const [sHours, minutes] = time24.match(/([0-9]{1,2}):([0-9]{2})/).slice(1);
      const period = +sHours < 12 ? 'AM' : 'PM';
      const hours = +sHours % 12 || 12;
    
      return `${hours}:${minutes} ${period}`;
    }
    
    const convertFrom12To24Format = (time12) => {
      const [sHours, minutes, period] = time12.match(/([0-9]{1,2}):([0-9]{2}) (AM|PM)/).slice(1);
      const PM = period === 'PM';
      const hours = (+sHours % 12) + (PM ? 12 : 0);
    
      return `${('0' + hours).slice(-2)}:${minutes}`;
    }
    

提交回复
热议问题