2013-02-26 85 views
33

是否有任何简单的方法来转换12小时hh:毫米上午/下午到24小时hh:毫米使用jquery?转换12小时hh:毫米上午/下午到24小时hh:毫米

注意:不使用其他库。

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

+3

'如果(小时<12)小时=小时+ 12;' – adeneo 2013-02-26 07:24:49

+0

如果为12添加一种特殊情况:XX AM(减去12),那么这是所有PM小时正确。对于所有其他AM时间,您不必做任何事情。 – devnull69 2013-02-26 07:38:47

回答

50

试试这个

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); 
+6

这是一个jsfiddle:http://jsfiddle.net/L2y2d/1/ – 2013-10-21 20:38:12

+1

失败,例如对于下午10点 – pie6k 2016-05-13 16:49:23

+1

OP特别要求hh:mm XX格式,所以晚上10点应该是晚上10点,它会工作 – devnull69 2016-05-13 21:51:03

16

我必须做同样的事情,但我产生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) 
9

这里我的解决方案,包括秒钟:

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]; 
    }; 
+1

'hours + = 12'和'hours - = 12' :-) – clearlight 2015-12-10 08:21:18

0

我创建了一个有点提交脚本@ 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())); 
}); 
+1

功能只适用于'PM'时间而不是'AM'时间。 [示例](http://jsbin.com/qovoyudunu/edit?js输出) – Sandeep 2016-05-18 09:59:30

+0

这是由于关于'||'和'&&'的运算符优先级错误。它应该是if((AMPM =='PM'|| AMPM =='pm')&& hours <12)'和'else if((AMPM =='AM'|| AMPM ==“am”)&&小时== 12)'。第三个正则表达式也是错误的。试试'var AMPM = time.match(/ \ s(AM | PM)$/i)[1];'。看到小提琴:http://jsbin.com/xanubinoqi/edit?js输出 – devnull69 2016-11-24 12:02:46

2

我需要这个功能的一个项目。我尝试了devnull69's,但是我遇到了一些麻烦,主要是因为字符串输入对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; 
    } 
} 
+0

这将失败的任何无效的值,如'99:99' – r3wt 2016-08-18 20:48:28

0
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"/> 
+0

你还可以添加一个解释? – Robert 2015-06-05 07:57:21

3

这将帮助:

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" 

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

-1
dateFormat.masks.armyTime= 'HH:MM'; 

now.format("armyTime"); 
0
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)/, ''); 
} 
+0

这没有任何作用... – MizAkita 2016-09-18 19:49:41

+0

也许是因为你没有正确传递参数“时间”,这对我来说完美无缺@MizAkita – 2017-01-09 17:07:44

0
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 
+0

欢迎来到Stack Overflow!虽然这个答案可能是正确和有用的,但如果你[包括一些解释一起](http://meta.stackexchange.com/q/114762/159034)来解释它是如何帮助解决这个问题的话,它是首选。如果有变化(可能不相关)导致其停止工作,读者需要了解它曾经如何工作,这在未来变得特别有用。 – 2016-10-09 19:45:14

11

这个问题需要基于满足CodeSkill #1

验证准则更新的答案:)

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

+0

if(hours ==='12'){ hours ='00'; } 难道你不想在这里检查修饰符吗? (AM或PM) if(hours ==='12'&& modifier ==='AM'){ hours ='00'; } – 2016-12-03 08:11:57

+0

@GregRTaylor不,那么它会输出例如。 12点12分的'24:12'。 – 2016-12-03 13:09:30

+0

伟大的解决方案。谢谢! – Dylan 2017-08-29 20:38:59

1

格式的n应是另一个功能:)


 

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

0

你可以试试这个更通用的功能:

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

-2

我要推荐一库: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')); 
+0

对不起,我会显示代码.. – kazaff 2016-12-09 02:27:36

0
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); 
0
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)/, ''); 
} 

呼叫用绳子PARAMS功能:

timeConversion('17:05:45AM') 

timeConversion('07:05:45PM') 
0

如果您正在寻找将任何格式转换为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 
相关问题