我需要一個函數來將文本中的時間從具有日期字母的格式轉換爲數字。 例如4:15 PM - > 16:15,4:15 AM - > 4:15 AM。目前,我有以下解決方案在JavaScript中繁瑣的時間解析
function formatTime(text){
\t var find = '([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9] (AM|PM)';
\t
\t var reg = new RegExp(find, 'g');
\t
\t pos = 0;
\t var result;
\t var formatedText = "";
\t while((result = reg.exec(text)) !== null) {
\t \t if(result[2] == "PM"){
\t \t \t var hours= parseInt(result[0], 10);
\t \t \t hours = hours + 12;
\t \t \t var hoursStr = hours.toString();
\t \t \t var newTime = hoursStr + result[0].substring(result[1].length,result[0].length - 3);
\t \t \t
\t \t \t formatedText += newTime;
\t \t \t pos = reg.lastIndex;
\t \t } else {
\t \t \t formatedText += text.replace("AM","").substring(pos, reg.lastIndex);
\t \t \t pos = reg.lastIndex;
\t \t }
\t }
\t
\t if(pos < text.length){
\t \t formatedText += text.substring(pos, text.length);
\t }
\t
\t return formatedText;
}
console.log(formatTime("Some Text (11:00AM - 1:00PM)"));
我做很好的情況下,像 的console.log(formatTime( 「有些文字(11:00 AM - 1:00 PM)」));但是我努力讓它進程 console.log(formatTime(「Some Text(11:00 AM - 1:00 PM)」));
http://stackoverflow.com/questions/14415618/replace-military-time-to-normal-time-with-javascript – mike510a
*例如4:15 PM - > 16:15,4:15 AM - > 4:15 AM因此,如果是PM,您想要轉換小時,但如果是AM,您希望在結果中留下**「AM」「 ? –
是的,我需要這樣的格式。 – Helga