Javascript 将12小时小时小时:毫米上午/下午转换为24小时小时小时:毫米

Javascript 将12小时小时小时:毫米上午/下午转换为24小时小时小时:毫米,javascript,jquery,Javascript,Jquery,是否有任何简单的方法可以使用jquery将12小时的hh:mm AM/PM转换为24小时的hh:mm 注意:不使用任何其他库 我有一个var time=$(“#starttime”).val()返回一个hh:mm AM/PM。试试这个 var time = $("#starttime").val(); var hours = Number(time.match(/^(\d+)/)[1]); var minutes = Number(time.match(/:(\d+)/)[1]); var AM

是否有任何简单的方法可以使用jquery将12小时的hh:mm AM/PM转换为24小时的hh:mm

注意:不使用任何其他库

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

试试这个

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);
var-time=$(“#starttime”).val();
var小时数=数量(time.match(/^(\d+/)[1]);
var minutes=Number(time.match(/:(\d+/)[1]);
var AMPM=time.match(/\s(.*)$/)[1];

如果(AMPM==“PM”&&hours我必须做一些类似的事情,但是我生成了一个
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)/, '');
}
示例:

        $("#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)

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

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];
  };
函数转换为24小时(时间){
//将类似于10:05:23 PM的字符串转换为24小时格式,返回类似于[22,5,23]
变量时间=时间匹配(/(\d+):(\d+):(\d+)(\d+)(\w)/;
var小时=数量(时间[1]);
var分钟=数量(时间[2]);
var秒=数字(时间[3]);
var meridian=时间[4]。toLowerCase();
如果(子午线=‘p’&小时数<12){
小时数+=12;
}
否则如果(子午线='a'&&hours==12){
小时数-=12;
}
返回[小时、分钟、秒];
};

我对script@devnull69 submitted做了一些修改。我觉得对于我的应用程序来说,作为一个函数,它会更有用,可以返回我可以使用的值,然后用作变量

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()));
    });

});
$(文档).ready(函数(){
函数转换时间(time){
var hours=Number(time.match(/^(\d\d?/)[1]);
var minutes=Number(time.match(/:(\d\d?)/)[1]);
var AMPM=时间匹配(/\s(AM | PM)$/i)[1];
如果((AMPM='PM'| | AMPM='PM')&&hours<12){
小时=小时+12;
}
else if((AMPM='AM'| | AMPM==''AM')和&hours==12){
小时=小时-12;
}
var sHours=hours.toString();
var sMinutes=minutes.toString();
如果(小时<10){
sHours=“0”+sHours;
}
否则,如果(分钟<10){
sMinutes=“0”+sMinutes;
}
回击声+“:”+微笑;
}
$(“按钮”)。单击(函数(){
警报(convertTime($('#time_字段').val());
});
});

我在一个项目中需要这个函数。我尝试了devnull69,但遇到了一些问题,主要是因为字符串输入对于am/pm部分非常具体,我需要更改我的验证。我把Adrian p.的JSFIDLE弄得一团糟,最终得到了一个版本,该版本似乎更适合更广泛的日期格式.这是小提琴:

以下是函数:

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;
    }
}
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));
}   
函数转换时间格式(格式,str){
变量小时数=数量(str.match(/^(\d+/)[1]);
var minutes=数字(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'];
如果(pm.indexOf(AMPM)>=0&&hours<12)小时=hours+12;
如果(am.indexOf(AMPM)>=0&&hours==12)小时数=hours-12;
var sHours=hours.toString();
var sMinutes=minutes.toString();
如果(小时<10)寿=0“+寿;
如果(分钟<10)sMinutes=“0”+sMinutes;
如果(格式='0000'){
返回(喊叫+微笑);
}else if(格式==“00:00”){
返回(sHours+“:”+sMinutes);
}否则{
返回false;
}
}
函数getDisplayDatetime(){
var d=新日期(“2011年2月4日19:00”),
hh=d.getHours(),mm=d.getMinutes(),dd=“AM”,h=hh;
mm=(mm.toString().长度==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;
}
这将有助于:

 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"
更新: 注意:在“Time”和“am/pm”之间应该有一个时间字符串空间。

函数转换为24小时(Time){
time=time.toUpperCase();
var hours=parseInt(time.substr(0,2));
if(time.indexOf('AM')!=-1&&hours==12){
时间=时间。替换('12','0');
}
if(time.indexOf('PM')!=-1&&hours<12){
时间=时间。更换(小时,(小时+12));
}
返回时间。替换(/(上午|下午)/,“”);
}

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

const convertTime12to24=(time12h)=>{
常量[时间,修饰符]=时间12小时分割(“”);
让[hours,minutes]=time.split(“:”);
如果(小时数=='12'){
小时数='00';
}
如果(修饰符=='PM'){
小时=parseInt(小时,10)+12;
}
返回`${hours}:${minutes}`;
}
console.log(convertTime12到24('01:02 PM'));
console.log(convertTime12到24('05:06 PM');
console.log(convertTime12to24('12:00pm');
console.log(convertTime12to24('12:00am'))

格式验证应该是另一个函数:)


功能转换器TimeFrom12到24(timeStr){
var colon=timeStr.indexOf(':');
var小时数=timeStr.substr(0,冒号),
分钟=timeStr.substr(冒号+1,2),
meridian=timeStr.substr(冒号+4,2).toUpperCase();
var hoursInt=parseInt(小时,10),
偏移量=子午线='下午'?12:0;
如果(hoursInt==12){
hoursInt=偏移量;
}否则{
hoursInt+=偏移量;
}
返回时间int+“:”+分钟;
}
console.log(转换时间从12点到24点(“上午12:00”);
console.log(从12点到24点(“12:00pm”);
console.log(从12点到24点(“上午11:00”);
console.log(从12点到24点(“凌晨1:00”);

console.log(从12点到24点(“下午1:00”)您可以尝试此更通用的功能:

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;
    }
}
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功能。

我必须推荐一个库:

代码:

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'));


如果您正在寻找一种能够将任何格式正确转换为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
函数get24hTime(str){ str=String(str).toLowerCase().re
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));
}   
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'));
 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);
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')
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
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;
}
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(":");
   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();
                 }
            }
 <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)">
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; 
}
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}`;
}
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;
}
/*
 * Complete the timeConversion function below.
 */
function timeConversion(s) {
    /*
     * Write your code here.
     */
    if(s.endsWith("PM")) s=s.substring(0, s.indexOf("PM"))+ " PM";
    if(s.endsWith("AM")) s=s.substring(0, s.indexOf("AM"))+ " AM";

    const d=new Date("2000-01-01 " + s);

    if(s.endsWith("PM") && d.getHours()<12) d.setHours(12); 
    if(s.endsWith("AM") && d.getHours()===12) d.setHours(d.getHours()-12); 

    let result= (d.getHours() < 10 ?  "0" + d.getHours(): d.getHours())+ ":"+   
    (d.getMinutes() <10 ? "0"+ d.getMinutes(): d.getMinutes()) + ":" +     
    (d.getSeconds() <10 ? "0"+ d.getSeconds(): d.getSeconds());

    return result;

}

timeConversion("07:05:45PM")
Sample Test Case
Input
07:05:45PM
Expected Output
19:05:45
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'));
#include <bits/stdc++.h>

using namespace std;

int main(){
    string time;
    int hours,seconds,minutes;
    string merid;
    char delim;
    stringstream ss;

    cin >> time;
    ss << time;
    ss >> hours >> delim >> minutes >> delim >> seconds >> merid;

    if((merid=="PM"&&hours!=12)||(merid=="AM"&&hours==12))
        hours=(hours+12)%24;

    printf("%02d:%02d:%02d", hours, minutes, seconds);

    return 0;
}
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;
    }
}