转换时间字符串格式 [英] convert time string format
本文介绍了转换时间字符串格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将时间数据转换为JavaScript中的HH:mm:ss
格式.
我的代码有问题(请参见代码内的注释):
I want to convert time data to the format HH:mm:ss
in JavaScript.
I've got a problem in my code (see comments inside the code):
function parseTime(timeString){
var timeString = timeString.toLowerCase();
timeString = $.trim(timeString);
var regEx = /^([0-9]|1[0-9]|2[0-3])$/;
var regEx2 = /^([0-9]|1[0-9]|2[0-3])\.?([0-5][0-9])$/;
var regEx3 = /^([0-9]|1[0-2])(a|p|am|pm)$/;
var regEx4 = /^([1-9]|10|11|12)\.?([0-5][0-9])(a|p|am|pm)$/;
if(regEx.test(timeString)){
var hours = timeString;
if(hours.length == 1){
hours = '0' + hours;
}
return hours + ':00:00';
}
else if(regEx2.test(timeString)){
var hoursEndIndex, minutesStartIndex;
if(timeString.indexOf('.')){
hoursEndIndex = timeString.indexOf('.');
minutesStartIndex = timeString.indexOf('.') + 1;
}else if(timeString.length == 3){//Problem here timeString.length returns 3 but the code below isn't executed?
hoursEndIndex = 1;
minutesStartIndex = 1;
}else if(timeString.length == 4){//Same thing here?
hoursEndIndex = 2;
minutesStartIndex = 2;
return timeString.length;
}
var hours = timeString.substring(0, hoursEndIndex);
if(hours.length == 1){
hours = '0' + hours;
}
var minutes = timeString.substr(minutesStartIndex, 2);
return hours + ':' + minutes + ':00';
}
推荐答案
我认为您正在使用 indexOf
此处错误:
I think you are using indexOf
incorrectly here:
if(timeString.indexOf('.')){
从文档中:
返回可以在数组中找到给定元素的第一个索引;如果不存在,则返回-1.
Returns the first index at which a given element can be found in the array, or -1 if it is not present.
可能是这个意思:
if(timeString.indexOf('.') > -1) {
对于您的代码,即使字符串不包含点,第一个if
语句中的表达式也将为true.这意味着else if
语句将永远不会执行.
With your code the expression in the first if
statement will be true even if the string does not contain a dot. This means that the else if
statement will never be executed.
这篇关于转换时间字符串格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文