是否有任何簡單的方法來轉換12小時hh:毫米上午/下午到24小時hh:毫米使用jquery?轉換12小時hh:毫米上午/下午到24小時hh:毫米
注意:不使用其他庫。
我有一個var time = $("#starttime").val()
,它返回hh:mm AM/PM。
是否有任何簡單的方法來轉換12小時hh:毫米上午/下午到24小時hh:毫米使用jquery?轉換12小時hh:毫米上午/下午到24小時hh:毫米
注意:不使用其他庫。
我有一個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);
我必須做同樣的事情,但我產生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)
這裏我的解決方案,包括秒鐘:
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 + = 12'和'hours - = 12' :-) – clearlight 2015-12-10 08:21:18
我創建了一個有點提交腳本@ 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'時間。 [示例](http://jsbin.com/qovoyudunu/edit?js輸出) – Sandeep 2016-05-18 09:59:30
這是由於關於'||'和'&&'的運算符優先級錯誤。它應該是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
我需要這個功能的一個項目。我嘗試了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;
}
}
這將失敗的任何無效的值,如'99:99' – r3wt 2016-08-18 20:48:28
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"/>
你還可以添加一個解釋? – Robert 2015-06-05 07:57:21
這將幫助:
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"
更新: 注意:「時間」和「上午/下午」之間應該有時間字符串的空間。
dateFormat.masks.armyTime= 'HH:MM';
now.format("armyTime");
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 2016-09-18 19:49:41
也許是因爲你沒有正確傳遞參數「時間」,這對我來說完美無缺@MizAkita – 2017-01-09 17:07:44
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!雖然這個答案可能是正確和有用的,但如果你[包括一些解釋一起](http://meta.stackexchange.com/q/114762/159034)來解釋它是如何幫助解決這個問題的話,它是首選。如果有變化(可能不相關)導致其停止工作,讀者需要了解它曾經如何工作,這在未來變得特別有用。 – 2016-10-09 19:45:14
這個問題需要基於滿足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'));
if(hours ==='12'){ hours ='00'; } 難道你不想在這裏檢查修飾符嗎? (AM或PM) if(hours ==='12'&& modifier ==='AM'){ hours ='00'; } – 2016-12-03 08:11:57
@GregRTaylor不,那麼它會輸出例如。 12點12分的'24:12'。 – 2016-12-03 13:09:30
偉大的解決方案。謝謝! – Dylan 2017-08-29 20:38:59
格式的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"));
你可以試試這個更通用的功能:
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 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)/, '');
}
呼叫用繩子PARAMS功能:
timeConversion('17:05:45AM')
或
timeConversion('07:05:45PM')
如果您正在尋找將任何格式轉換爲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
'如果(小時<12)小時=小時+ 12;' – adeneo 2013-02-26 07:24:49
如果爲12添加一種特殊情況:XX AM(減去12),那麼這是所有PM小時正確。對於所有其他AM時間,您不必做任何事情。 – devnull69 2013-02-26 07:38:47