What's a simple way to convert between an am/pm time to 24 hour time in javascript

前端 未结 5 1151
独厮守ぢ
独厮守ぢ 2021-02-03 15:51

I\'ve been playing with jquery and I\'ve run myself into a time problem. I\'ve got 3 time input select boxes, one for hours, one for minutes, and one for the Meridian. I need to

5条回答
  •  温柔的废话
    2021-02-03 16:43

    Just to add a plain JS answer, the following will format the time based on the length of the initial string. If h:mm returns HH:mm, if h:mm:ss returns HH:mm:ss.

    If HH:mm:ss is always required, it's simple to add default seconds of ":00" if not present in initial string.

    // Change time in h:mm:ss ap to  HH:mm:ss time
    // If time missing seconds, returns HH:mm
    function timeToHHmm(time) {
      var nums = time.match(/\d+/g);
      var am   = /am/i.test(time);
      nums[0] = ('0' + ((nums[0]%12) + (am? 0 : 12))).slice(-2);
      // If HH:mm:ss required, use following line instead of last
      // return nums.join(':') + (nums.length == 2? ':00' : '');
      return nums.join(':');
    }
    
    // Some tests
    ['2:45am',     // hh:mm only
     '5:15:45pm',  // hh:mm:ss
     '5:15:45 pm', // space before am/pm
     '05:15:45 pm',// leading zero on hour
     '12:02am',
     '12:02 pm',
     '12:02:00am'
     ].forEach(function(time) {
      console.log(time + ' => ' + timeToHHmm(time));
    });

提交回复
热议问题