【问题标题】:convert 12-hour hh:mm AM/PM to 24-hour hh:mm将 12 小时 hh:mm AM/PM 转换为 24 小时 hh:mm
【发布时间】:2013-02-26 07:23:12
【问题描述】:

有没有使用 jquery 将 12 小时 hh:mm AM/PM 转换为 24 小时 hh:mm 的简单方法?

注意:不使用任何其他库。

我有一个var time = $("#starttime").val(),它返回一个 hh:mm AM/PM。

【问题讨论】:

  • if (hour < 12) hour = hour + 12;
  • 如果您为上午 12:xx 添加一个特殊情况(减去 12),那么这对于所有下午时间都是正确的。对于所有其他上午时间,您无需执行任何操作。

标签: javascript jquery


【解决方案1】:

试试这个

var time = $("#starttime").val();
var hours = Number(time.match(/^(\d+)/)[1]);
var minutes = Number(time.match(/:(\d+)/)[1]);
var AMPM = time.match(/\s(.*)$/)[1];
if(AMPM == "PM" && hours<12) hours = hours+12;
if(AMPM == "AM" && hours==12) hours = hours-12;
var sHours = hours.toString();
var sMinutes = minutes.toString();
if(hours<10) sHours = "0" + sHours;
if(minutes<10) sMinutes = "0" + sMinutes;
alert(sHours + ":" + sMinutes);

【讨论】:

  • 例如晚上 10 点失败
  • OP 专门要求 hh:mm XX 格式,所以晚上 10 点应该是晚上 10:00,它会工作
  • if(AMPM == "AM" &amp;&amp; hours==12) hours = 0; 我猜更直接
  • 我也会推荐(AMPM.toLowerCase() == "am")
  • 你的回答让我处于危急关头。继续做好这项工作。谢谢你的回答。实际上我需要在另外 10 分钟内交付我的项目,但我是花几秒钟欣赏你
【解决方案2】:

这个问题需要一个更新的答案:)

const convertTime12to24 = (time12h) => {
  const [time, modifier] = time12h.split(' ');

  let [hours, minutes] = time.split(':');

  if (hours === '12') {
    hours = '00';
  }

  if (modifier === 'PM') {
    hours = parseInt(hours, 10) + 12;
  }

  return `${hours}:${minutes}`;
}

console.log(convertTime12to24('01:02 PM'));
console.log(convertTime12to24('05:06 PM'));
console.log(convertTime12to24('12:00 PM'));
console.log(convertTime12to24('12:00 AM'));

【讨论】:

  • if (hours === '12') { hours = '00';你不想在这里检查修饰符吗? (上午或下午)如果(小时 === '12' && 修饰符 === '上午'){ 小时 = '00'; }
  • @GregRTaylor 否,那么它将输出例如。 24:1212:12 PM
  • 上午 12:00 示例的代码错误:修复 if (hours === '12' && modifier === 'PM') { hours = '00'; } , PM = post meridiem so 下午
  • @snow 答案可能已更改,但现在它给出了凌晨 12 点的 00:00,所以它似乎没有问题
  • @Learner 它没有被改变。它一直在正常工作:)
【解决方案3】:

我不得不做类似的事情,但我正在生成一个 Date 对象,所以我最终制作了一个这样的函数:

function convertTo24Hour(time) {
    var hours = parseInt(time.substr(0, 2));
    if(time.indexOf('am') != -1 && hours == 12) {
        time = time.replace('12', '0');
    }
    if(time.indexOf('pm')  != -1 && hours < 12) {
        time = time.replace(hours, (hours + 12));
    }
    return time.replace(/(am|pm)/, '');
}

我认为这读起来容易一些。您输入格式为 h:mm am/pm 的字符串。

    var time = convertTo24Hour($("#starttime").val().toLowerCase());
    var date = new Date($("#startday").val() + ' ' + time);

例子:

        $("#startday").val('7/10/2013');

        $("#starttime").val('12:00am');
        new Date($("#startday").val() + ' ' + convertTo24Hour($("#starttime").val().toLowerCase()));
        Wed Jul 10 2013 00:00:00 GMT-0700 (PDT)

        $("#starttime").val('12:00pm');
        new Date($("#startday").val() + ' ' + convertTo24Hour($("#starttime").val().toLowerCase()));
        Wed Jul 10 2013 12:00:00 GMT-0700 (PDT)

        $("#starttime").val('1:00am');
        new Date($("#startday").val() + ' ' + convertTo24Hour($("#starttime").val().toLowerCase()));
        Wed Jul 10 2013 01:00:00 GMT-0700 (PDT)

        $("#starttime").val('12:12am');
        new Date($("#startday").val() + ' ' + convertTo24Hour($("#starttime").val().toLowerCase()));
        Wed Jul 10 2013 00:12:00 GMT-0700 (PDT)

        $("#starttime").val('3:12am');
        new Date($("#startday").val() + ' ' + convertTo24Hour($("#starttime").val().toLowerCase()));
        Wed Jul 10 2013 03:12:00 GMT-0700 (PDT)

        $("#starttime").val('9:12pm');
        new Date($("#startday").val() + ' ' + convertTo24Hour($("#starttime").val().toLowerCase()));
        Wed Jul 10 2013 21:12:00 GMT-0700 (PDT)

【讨论】:

  • 当 AM 或 PM 为大写字母时存在错误
【解决方案4】:

这会有所帮助:

 function getTwentyFourHourTime(amPmString) { 
        var d = new Date("1/1/2013 " + amPmString); 
        return d.getHours() + ':' + d.getMinutes(); 
    }

示例:

getTwentyFourHourTime("8:45 PM"); // "20:45"
getTwentyFourHourTime("8:45 AM"); // "8:45"

更新: 注意:“时间”和“上午/下午”之间应该有时间字符串的空格。

【讨论】:

  • According to MDN 使用带有字符串的 Date 构造函数“由于浏览器的差异和不一致,强烈建议不要这样做”。
【解决方案5】:

这是我的解决方案,包括秒数:

function convert_to_24h(time_str) {
    // Convert a string like 10:05:23 PM to 24h format, returns like [22,5,23]
    var time = time_str.match(/(\d+):(\d+):(\d+) (\w)/);
    var hours = Number(time[1]);
    var minutes = Number(time[2]);
    var seconds = Number(time[3]);
    var meridian = time[4].toLowerCase();

    if (meridian == 'p' && hours < 12) {
      hours += 12;
    }
    else if (meridian == 'a' && hours == 12) {
      hours -= 12;
    }
    return [hours, minutes, seconds];
  };

【讨论】:

  • hours += 12hours -= 12 :-)
【解决方案6】:

我必须推荐一个图书馆:Moment

代码:

var target12 = '2016-12-08 9:32:45 PM';
console.log(moment(target12, 'YYYY-MM-DD h:m:s A').format('YYYY-MM-DD HH:mm:ss'));

【讨论】:

  • 我不确定为什么这个答案没有得到支持,但这是最正确的方法,因为时刻会为您处理时区和一切!接受我的投票
【解决方案7】:

我在一个项目中需要这个功能。我尝试了 devnull69,但遇到了一些麻烦,主要是因为字符串输入对于 am/pm 部分非常具体,我需要更改我的验证。我弄乱了 Adrian P. 的 jsfiddle,最终得到了一个似乎更适合各种日期格式的版本。这是小提琴:http://jsfiddle.net/u91q8kmt/2/

函数如下:

function ConvertTimeformat(format, str) {
    var hours = Number(str.match(/^(\d+)/)[1]);
    var minutes = Number(str.match(/:(\d+)/)[1]);
    var AMPM = str.match(/\s?([AaPp][Mm]?)$/)[1];
    var pm = ['P', 'p', 'PM', 'pM', 'pm', 'Pm'];
    var am = ['A', 'a', 'AM', 'aM', 'am', 'Am'];
    if (pm.indexOf(AMPM) >= 0 && hours < 12) hours = hours + 12;
    if (am.indexOf(AMPM) >= 0 && hours == 12) hours = hours - 12;
    var sHours = hours.toString();
    var sMinutes = minutes.toString();
    if (hours < 10) sHours = "0" + sHours;
    if (minutes < 10) sMinutes = "0" + sMinutes;
    if (format == '0000') {
        return (sHours + sMinutes);
    } else if (format == '00:00') {
        return (sHours + ":" + sMinutes);
    } else {
        return false;
    }
}

【讨论】:

  • 这对于任何无效值(例如 '99:99')都会失败
【解决方案8】:
function timeConversion(s) {
  var time = s.toLowerCase().split(':');
  var hours = parseInt(time[0]);
  var _ampm = time[2];
  if (_ampm.indexOf('am') != -1 && hours == 12) {
    time[0] = '00';
  }
  if (_ampm.indexOf('pm')  != -1 && hours < 12) {
    time[0] = hours + 12;
  }
  return time.join(':').replace(/(am|pm)/, '');
}

使用字符串参数调用函数:

timeConversion('17:05:45AM')

timeConversion('07:05:45PM')

【讨论】:

    【解决方案9】:

    如果您正在寻找将 ANY FORMAT 正确转换为 24 小时 HH:MM 的解决方案。

    function get24hTime(str){
        str = String(str).toLowerCase().replace(/\s/g, '');
        var has_am = str.indexOf('am') >= 0;
        var has_pm = str.indexOf('pm') >= 0;
        // first strip off the am/pm, leave it either hour or hour:minute
        str = str.replace('am', '').replace('pm', '');
        // if hour, convert to hour:00
        if (str.indexOf(':') < 0) str = str + ':00';
        // now it's hour:minute
        // we add am/pm back if striped out before 
        if (has_am) str += ' am';
        if (has_pm) str += ' pm';
        // now its either hour:minute, or hour:minute am/pm
        // put it in a date object, it will convert to 24 hours format for us 
        var d = new Date("1/1/2011 " + str);
        // make hours and minutes double digits
        var doubleDigits = function(n){
            return (parseInt(n) < 10) ? "0" + n : String(n);
        };
        return doubleDigits(d.getHours()) + ':' + doubleDigits(d.getMinutes());
    }
    
    console.log(get24hTime('6')); // 06:00
    console.log(get24hTime('6am')); // 06:00
    console.log(get24hTime('6pm')); // 18:00
    console.log(get24hTime('6:11pm')); // 18:11
    console.log(get24hTime('6:11')); // 06:11
    console.log(get24hTime('18')); // 18:00
    console.log(get24hTime('18:11')); // 18:11
    

    【讨论】:

      【解决方案10】:

      有了它,您可以拥有以下内容: 示例输入:07:05:45PM 示例输出:19:05:45

      function timeConversion(s) {
          let output = '';
          const timeSeparator = ':'
          const timeTokenType = s.substr(s.length - 2 , 2).toLowerCase();
          const timeArr = s.split(timeSeparator).map((timeToken) => {
          const isTimeTokenType = 
                timeToken.toLowerCase().indexOf('am') > 0 ||                                                                                               
                 timeToken.toLowerCase().indexOf('pm');
              if(isTimeTokenType){
                  return timeToken.substr(0, 2);
              } else {
                  return timeToken;
              }
          });
          const hour = timeArr[0];
          const minutes = timeArr[1];
          const seconds = timeArr[2];
          const hourIn24 = (timeTokenType === 'am') ? parseInt(hour) - 12 : 
          parseInt(hour) + 12;
          return hourIn24.toString()+ timeSeparator + minutes + timeSeparator + seconds;
      }
      

      希望你喜欢!

      【讨论】:

        【解决方案11】:

        对于以后阅读本文的任何人,这里有一个更简单的答案:

        var s = "11:41:02PM";
        var time = s.match(/\d{2}/g);
        if (time[0] === "12") time[0] = "00";
        if (s.indexOf("PM") > -1) time[0] = parseInt(time[0])+12;
        return time.join(":");
        

        【讨论】:

          【解决方案12】:

          基于会议CodeSkill #1

          格式验证应该是另一个功能:)

            
          
          function convertTimeFrom12To24(timeStr) {
            var colon = timeStr.indexOf(':');
            var hours = timeStr.substr(0, colon),
                minutes = timeStr.substr(colon+1, 2),
                meridian = timeStr.substr(colon+4, 2).toUpperCase();
           
            
            var hoursInt = parseInt(hours, 10),
                offset = meridian == 'PM' ? 12 : 0;
            
            if (hoursInt === 12) {
              hoursInt = offset;
            } else {
              hoursInt += offset;
            }
            return hoursInt + ":" + minutes;
          }
          console.log(convertTimeFrom12To24("12:00 AM"));
          console.log(convertTimeFrom12To24("12:00 PM"));
          console.log(convertTimeFrom12To24("11:00 AM"));
          console.log(convertTimeFrom12To24("01:00 AM"));
          console.log(convertTimeFrom12To24("01:00 PM"));

          【讨论】:

            【解决方案13】:

            @krzysztof 答案的扩展版本,能够在时间和修饰符之间有或没有空间的时间工作。

            const convertTime12to24 = (time12h) => {
                  const [fullMatch, time, modifier] = time12h.match(/(\d?\d:\d\d)\s*(\w{2})/i);
            
                  let [hours, minutes] = time.split(':');
            
                  if (hours === '12') {
                    hours = '00';
                  }
            
                  if (modifier === 'PM') {
                    hours = parseInt(hours, 10) + 12;
                  }
            
                  return `${hours}:${minutes}`;
                }
            
                console.log(convertTime12to24('01:02 PM'));
                console.log(convertTime12to24('05:06 PM'));
                console.log(convertTime12to24('12:00 PM'));
                console.log(convertTime12to24('12:00 AM'));
            

            【讨论】:

              【解决方案14】:

              将 AM/PM 时间字符串转换为 24 小时格式。 示例 9:30 PM 到 21:30

              function get24HrsFrmAMPM(timeStr) {
                  if (timeStr && timeStr.indexOf(' ') !== -1 && timeStr.indexOf(':') !== -1) {
                      var hrs = 0;
                      var tempAry = timeStr.split(' ');
                      var hrsMinAry = tempAry[0].split(':');
                      hrs = parseInt(hrsMinAry[0], 10);
                      if ((tempAry[1] == 'AM' || tempAry[1] == 'am') && hrs == 12) {
                          hrs = 0;
                      } else if ((tempAry[1] == 'PM' || tempAry[1] == 'pm') && hrs != 12) {
                          hrs += 12;
                      }
                      return ('0' + hrs).slice(-2) + ':' + ('0' + parseInt(hrsMinAry[1], 10)).slice(-2);
                  } else {
                      return null;
                  }
              }
              

              【讨论】:

                【解决方案15】:

                计算时间 12 小时到 24 小时的单行代码

                任何格式的输入都可以正常工作

                const convertTime12to24 = (time12h) => moment(time12h, 'hh:mm A').format('HH:mm');
                
                console.log(convertTime12to24('06:30 pm'));
                
                console.log(convertTime12to24('06:00 am'));
                
                console.log(convertTime12to24('9:00 am'));
                
                console.log(convertTime12to24('9pm')); 
                &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"&gt;&lt;/script&gt;

                【讨论】:

                  【解决方案16】:
                    function getDisplayDatetime() {
                      var d = new Date("February 04, 2011 19:00"),
                       hh = d.getHours(),  mm = d.getMinutes(),  dd = "AM", h = hh;
                      mm=(mm.toString().length == 1)? mm = "0" + mm:mm;
                      h=(h>=12)?hh-12:h;
                       dd=(hh>=12)?"PM":"AM";
                      h=(h == 0)?12:h;
                      var textvalue=document.getElementById("txt");
                      textvalue.value=h + ":" + mm + " " + dd;
                  }
                  
                  </script>
                  </head>
                  <body>
                  <input type="button" value="click" onclick="getDisplayDatetime()">
                  <input type="text" id="txt"/>
                  

                  【讨论】:

                    【解决方案17】:
                    dateFormat.masks.armyTime= 'HH:MM';
                    
                    now.format("armyTime");
                    

                    【讨论】:

                      【解决方案18】:
                      function convertTo24Hour(time) {
                          time = time.toUpperCase();
                          var hours = parseInt(time.substr(0, 2));
                          if(time.indexOf('AM') != -1 && hours == 12) {
                              time = time.replace('12', '0');
                          }
                          if(time.indexOf('PM')  != -1 && hours < 12) {
                              time = time.replace(hours, (hours + 12));
                          }
                          return time.replace(/(AM|PM)/, '');
                      }
                      

                      【讨论】:

                      • 可能是因为您没有正确传递参数“时间”,这对我来说非常有效@MizAkita
                      【解决方案19】:
                      date --date="2:00:01 PM" +%T
                      14:00:01
                      
                      date --date="2:00 PM" +%T | cut -d':' -f1-2
                      14:00
                      
                      var="2:00:02 PM"
                      date --date="$var" +%T
                      14:00:02
                      

                      【讨论】:

                      • 欢迎来到 Stack Overflow!尽管此答案可能是正确且有用的,但如果您 include some explanation along with it 解释它如何帮助解决问题,则最好。这在未来变得特别有用,如果有一个变化(可能不相关)导致它停止工作并且读者需要了解它曾经是如何工作的。
                      【解决方案20】:

                      你可以试试这个更通用的函数:

                      function from12to24(hours, minutes, meridian) {
                        let h = parseInt(hours, 10);
                        const m = parseInt(minutes, 10);
                        if (meridian.toUpperCase() === 'PM') {
                          h = (h !== 12) ? h + 12 : h;
                        } else {
                          h = (h === 12) ? 0 : h;
                        }
                        return new Date((new Date()).setHours(h,m,0,0));
                      }   
                      

                      注意它使用了一些 ES6 功能。

                      【讨论】:

                        【解决方案21】:
                         var time = "9:09:59AM"
                            var pmCheck =time.includes("PM");
                            var hrs=parseInt(time.split(":")[0]);
                            var newtime='';
                            // this is for between  12 AM to 12:59:59AM  = 00:00:00
                            if( hrs == 12  && pmCheck == false){
                                newtime= "00" +':'+ time.split(":")[1] +':'+ time.split(":")[2].replace("AM",'');
                                }
                            //this is for between  12 PM to 12:59:59 =12:00:00
                            else if (hrs == 12  && pmCheck == true){
                                     newtime= "12" +':'+ time.split(":")[1] +':'+ time.split(":")[2].replace("PM",'');
                            }
                            //this is for between 1 AM and 11:59:59 AM
                            else if (!pmCheck){
                                newtime= hrs +':'+ time.split(":")[1] +':'+ time.split(":")[2].replace("AM",'');
                            }
                            //this is for between 1 PM and 11:59:59 PM
                            else if(pmCheck){
                                newtime= (hrs +12)+':'+ time.split(":")[1] +':'+ time.split(":")[2].replace("PM",'');
                            }
                            console.log(newtime);
                        

                        【讨论】:

                          【解决方案22】:

                          我已经对提交的@devnull69 脚本进行了一些改编。我觉得对于我的应用程序,它作为一个函数会更有用,它可以返回我可以返回的值,然后用作变量。

                          HTML

                          <input type="text" id="time_field" />
                          <button>Submit</submit>
                          

                          jQuery

                          $(document).ready(function() {
                          
                              function convertTime(time) {
                          
                                  var hours = Number(time.match(/^(\d\d?)/)[1]);
                                  var minutes = Number(time.match(/:(\d\d?)/)[1]);
                                  var AMPM = time.match(/\s(AM|PM)$/i)[1];
                          
                                  if((AMPM == 'PM' || AMPM == 'pm') && hours < 12) {
                                      hours = hours + 12;
                                  }
                                  else if((AMPM == 'AM' || AMPM == "am") && hours == 12) {
                                      hours = hours - 12;
                                  }
                          
                                  var sHours = hours.toString();
                                  var sMinutes = minutes.toString();
                          
                                  if(hours < 10) {
                                      sHours = "0" + sHours;
                                  }
                                  else if(minutes < 10) {
                                       sMinutes = "0" + sMinutes;
                                  }
                          
                                  return sHours + ":" + sMinutes;
                          
                              }
                          
                              $('button').click(function() {
                                  alert(convertTime($('#time_field').val()));
                              });
                          
                          });
                          

                          【讨论】:

                          • 该功能仅适用于PM 时间而不是AM 时间。 Example
                          • 这是由于关于||&amp;&amp; 的错误操作员优先级。它应该是if ( (AMPM == 'PM' || AMPM == 'pm') &amp;&amp; hours&lt;12)else if ( (AMPM == 'AM' || AMPM == "am") &amp;&amp; hours==12)。第三个正则表达式也是错误的。试试var AMPM = time.match(/\s(AM|PM)$/i)[1];。见小提琴:jsbin.com/xanubinoqi/edit?js,output
                          • 大获成功@devnull69。我已更新代码以反映您的建议。
                          【解决方案23】:

                          一个简单的js函数实时计算时间经络

                          JS

                             function convertTime24to12(time24h) {
                                          var timex = time24h.split(':');
                          
                                          if(timex[0] !== undefined && timex [1] !== undefined)
                                           {
                                               var hor = parseInt(timex[0]) > 12 ? (parseInt(timex[0])-12) : timex[0] ;
                                               var minu = timex[1];
                                               var merid = parseInt(timex[0]) < 12 ? 'AM' : 'PM';
                          
                                               var res = hor+':'+minu+' '+merid;
                          
                                               document.getElementById('timeMeridian').innerHTML=res.toString();
                                           }
                                      }
                          

                          HTML

                           <label for="end-time">Hour <i id="timeMeridian"></i> </label>
                                      <input type="time" name="hora" placeholder="Hora" id="end-time" class="form-control" onkeyup="convertTime24to12(this.value)">
                          

                          【讨论】:

                            【解决方案24】:

                            基于@krzysztof-dąbrowski 的answer 的打字稿解决方案

                            export interface HoursMinutes {
                              hours: number;
                              minutes: number;
                            }
                            export function convert12to24(time12h: string): HoursMinutes {
                              const [time, modifier] = time12h.split(' ');
                              let [hours, minutes] = time.split(':');
                            
                              if (hours === '12') {
                                hours = '00';
                              }
                            
                              if (minutes.length === 1) {
                                minutes = `0${minutes}`;
                              }
                            
                              if (modifier.toUpperCase() === 'PM') {
                                hours = parseInt(hours, 10) + 12 + '';
                              }
                            
                              return {
                                hours: parseInt(hours, 10),
                                minutes: parseInt(minutes, 10)
                              };
                            }
                            

                            【讨论】:

                              【解决方案25】:

                              针对所有用例进行测试

                              function timeConversion(s) {
                              let h24;
                              let m24;
                              let sec24;
                              
                              const splittedDate = s.split(":");
                              const h = parseInt(splittedDate[0], 10);
                              const m = parseInt(splittedDate[1], 10);
                              const sec = parseInt(splittedDate[2][0] + splittedDate[2][1], 10); 
                              const meridiem = splittedDate[2][2] + splittedDate[2][3];
                              
                              if (meridiem === "AM") {
                                  if (h === 12) {
                                      h24 = '00';
                                  } else {
                                      h24 = h;
                                      if (h24 < 10) {
                                          h24 = '0' + h24;
                                      }
                                  }
                                  m24 = m;
                                  sec24 = sec;
                              } else if (meridiem === "PM") {
                                  if (h === 12) {
                                      h24 = h
                                  } else {
                                      h24 = h + 12;
                                      if (h24 < 10) {
                                          h24 = '0' + h24;
                                      }
                                  }
                                  m24 = m;
                                  sec24 = sec;
                              }
                              
                              
                              if (m24 < 10) {
                                  m24 = '0' + m24; 
                              } 
                              
                              if (sec24 < 10) {
                                  sec24 = '0' + sec24;
                              }
                              
                                return h24 + ":" + m24 + ":" + sec24; 
                              }
                              

                              Here is the jsfiddle working example

                              【讨论】:

                                【解决方案26】:

                                短 ES6 代码

                                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}`;
                                }
                                
                                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}`;
                                }
                                

                                【讨论】:

                                  【解决方案27】:

                                  我刚刚在 HackerRank 上解决了这个问题,所以我在这里分享我的结果

                                  function timeConversion(s) {
                                      const isPM = s.indexOf('PM') !== -1;
                                      let [hours, minutes, seconds] = s.replace(isPM ? 'PM':'AM', '').split(':');
                                  
                                      if (isPM) {
                                          hours = parseInt(hours, 10) + 12;
                                          hours = hours === 24 ? 12 : hours;
                                      } else {
                                          hours = parseInt(hours, 10);
                                          hours = hours === 12 ? 0 : hours;
                                          if (String(hours).length === 1) hours = '0' + hours;
                                      }
                                  
                                      const time = [hours, minutes, seconds].join(':');
                                  
                                      return time;
                                  }
                                  

                                  这适用于06:40:03AM 之类的输入。

                                  【讨论】:

                                    【解决方案28】:

                                    function formatto24(date) {
                                      let ampm = date.split(" ")[1];
                                      let time = date.split(" ")[0];
                                      if (ampm == "PM") {
                                        let hours = time.split(":")[0];
                                        let minutes = time.split(":")[1];
                                        let seconds = time.split(":")[2];
                                        let hours24 = JSON.parse(hours) + 12;
                                        return hours24 + ":" + minutes + ":" + seconds;
                                      } else {
                                        return time;
                                      }
                                    }

                                    【讨论】:

                                      【解决方案29】:

                                      我就是这样实现的:

                                      function timeConversion(s) {
                                          // Write your code here
                                         const arr =s.split(":")
                                         const isAM = arr[2].includes("AM")
                                         if(isAM) {
                                            arr[0]=arr[0].padStart(2, '0');
                                            arr[2]=arr[2].replace("AM","");  
                                              if(arr[0]==="12")  arr[0] ="00"
                                                 
                                          }else{
                                              arr[0]=(+arr[0]+12).toString();
                                              arr[2]=arr[2].replace("PM","");  
                                              if(arr[0]==="24")  arr[0] ="12"
                                          }
                                         return(arr.join(":"))
                                      }
                                      

                                      【讨论】:

                                        【解决方案30】:

                                        我发现这是最简单的方法。以下是正在发生的事情的分步说明:

                                        1. 你会得到 12 小时格式的时间

                                        2. 按时间戳和子午线划分时间

                                        3. 如果是午夜,则在前面加上 00,否则只打印时间戳

                                        4. 如果是中午,只需打印时间戳,否则使用12添加小时

                                        function timeConversion(s) {
                                            // 07:05:45PM
                                            const timeInAmPmArray = s.split(/(AM|PM)/) // ['07:05:45', 'PM', '']
                                            const hour = Number(timeInAmPmArray[0].split(':')[0]) // 7
                                            const amOrPm = timeInAmPmArray[1] // PM
                                            let timeIn24Hour = ''
                                            if(amOrPm === 'AM') {
                                              timeIn24Hour = hour === 12 ? `00:${timeInAmPmArray[0].split(':').slice(1).join(':')}` : timeInAmPmArray[0]
                                            } else {
                                              timeIn24Hour = hour === 12 ? timeInAmPmArray[0] : `${hour + 12}:${timeInAmPmArray[0].split(':').slice(1).join(':')}`
                                              // timeIn24Hour = 19:05:45
                                            }
                                            return timeIn24Hour
                                        }
                                            
                                        timeConversion('07:05:45PM')
                                        

                                        【讨论】:

                                        • 虽然此代码可能会回答问题,但提供有关它如何和/或为什么解决问题的额外上下文将提高​​答案的长期价值。您可以在帮助中心找到更多关于如何写好答案的信息:stackoverflow.com/help/how-to-answer。祝你好运?
                                        猜你喜欢
                                        • 1970-01-01
                                        • 1970-01-01
                                        • 2017-04-08
                                        • 1970-01-01
                                        • 1970-01-01
                                        • 2010-09-26
                                        • 1970-01-01
                                        • 2013-02-26
                                        • 2018-01-21
                                        相关资源
                                        最近更新 更多