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

前端 未结 16 1344
野性不改
野性不改 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]
    }))

    0 讨论(0)
  • 2020-11-30 04:12
    function timeformat(date1) {
      var date=new Date(date1);
      var month = date.toLocaleString('en-us', { month: 'long' });
      var mdate  =date.getDate();
      var year  =date.getFullYear();
      var hours = date.getHours();
      var minutes = date.getMinutes();
      var ampm = hours >= 12 ? 'pm' : 'am';
      hours = hours % 12;
      hours = hours ? hours : 12; // the hour '0' should be '12'
      minutes = minutes < 10 ? '0'+minutes : minutes;
      var strTime = mdate+"-"+month+"-"+year+" "+hours + ':' + minutes + ' ' + ampm;
      return strTime;
    }
    var ampm=timeformat("2019-01-11 12:26:43");
    console.log(ampm);
    

    Here the Function to Convert time into am or pm with Date,it may be help Someone.

    0 讨论(0)
  • 2020-11-30 04:13

    Based on gilly3's answer.

    If you want to convert:

     08:00 to 08:00 AM 
     16:00 to 04:00 PM
    

    Then this will work:

    function tConv24(time24) {
      var ts = time24;
      var H = +ts.substr(0, 2);
      var h = (H % 12) || 12;
      h = (h < 10)?("0"+h):h;  // leading 0 at the left for 1 digit hours
      var ampm = H < 12 ? " AM" : " PM";
      ts = h + ts.substr(2, 3) + ampm;
      return ts;
    };
    

    https://jsfiddle.net/fpjs9g0L/

    0 讨论(0)
  • 2020-11-30 04:13

    Researching this same question I have come across several complicated, hard to understand solutions, and then it dawned on me: There is a very simple solution that doesn't rely on hard-to-read regular expressions or other complicated code. Unless I am missing something obvious, this is an extremely simple, easy to understand solution:

    function timeTo12HrFormat(time)
    {   // Take a time in 24 hour format and format it in 12 hour format
        var time_part_array = time.split(":");
        var ampm = 'AM';
    
        if (time_part_array[0] >= 12) {
            ampm = 'PM';
        }
    
        if (time_part_array[0] > 12) {
            time_part_array[0] = time_part_array[0] - 12;
        }
    
        formatted_time = time_part_array[0] + ':' + time_part_array[1] + ':' + time_part_array[2] + ' ' + ampm;
    
        return formatted_time;
    }
    
    
    
    var time = timeTo12HrFormat(18:00:00);
    console.log(time);  // 6:00:00 PM
    
    0 讨论(0)
  • 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
    <h1 id='myTime'></h1>

    0 讨论(0)
  • 2020-11-30 04:15

    Thanks to @HBP for paving the way here!

    I found this to add a little flexibility to the solution.

    The RegEx has been updated to accommodate times before noon.

    This solution allows you to pass any string to it. As long as a valid time (in this format 18:00 || 18:00:00 || 3:00 || 3:00:00) is somewhere in that string, you're good to go.

    Note: you can use just the militaryToTweleveHourConverter or take the guts out of the parseTime variable. However, I'm formatting a date from a database with date-fns then passing that formatted date to the converter.

    Totally works. Hope this helps.

    import dateFns from 'date-fns';
    
    
    
    //* +---------------------------+
    //* Format ex. Sat 1/1/18 1:00pm
    //* +---------------------------+
    const formatMonthDayYearTime = date =>
      militaryToTweleveHourConverter(
        dateFns.format(new Date(date), 'ffffd M/DD/YY H:mm')
      );
    
    //* +-------------------------------+
    //* Convert MILITARY TIME to 12 hour
    //* +-------------------------------+
    const militaryToTweleveHourConverter = time => {
      const getTime = time.split(' ');
    
      const parseTime = getTime.map(res => {
        // Check for correct time format and split into components or return non-time units unaltered
        let timeUnit = res
          .toString()
          .match(/^([\d]|[0-1]\d|2[0-3])(:)([0-5]\d)(:[0-5]\d)?$/) || [res];
    
        console.log('timeUnit', timeUnit);
        // If the time format is matched, it will break the components into an array
        // ie. ["19:00", "19", ":", "00", undefined]
        if (timeUnit.length > 1) {
          // Remove full string match value
          timeUnit = timeUnit.slice(1);
          // Set am/pm and assign it to the last index in the array
          timeUnit[5] = timeUnit[0] < 12 ? 'am' : 'pm';
          // Adjust hours by subtracting 12 from anything greater than 12 and replace the value in the hours index
          timeUnit[0] = timeUnit[0] % 12 || 12;
        }
        // return adjusted time or original string
        return timeUnit.join('');
      });
      // Re-assemble the array pieces into a string
      return parseTime.join(' ');
    };
    
    
    console.log(formatMonthDayYearTime('Sat 9/17/18 18:30'));
    // console log returns the following
    // Mon 9/17/18 6:30pm
    
    console.log(militaryToTweleveHourConverter('18:30'));
    // console log returns the following
    // 6:30pm
    
    console.log(militaryToTweleveHourConverter('18:30:09'));
    // console log returns the following
    // 6:30:09pm
    
    console.log(militaryToTweleveHourConverter('8:30:09'));
    // console log returns the following
    // 8:30:09am
    
    0 讨论(0)
提交回复
热议问题