Convert time string format

I want to convert time data to a format HH:mm:ssin JavaScript. I have 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';
    }
+2
source share
4 answers

I think you are using indexOfhere:

if(timeString.indexOf('.')){

From the documentation:

Returns the first index at which the given element can be found in the array, or -1 if it is absent.

Perhaps you mean this:

if(timeString.indexOf('.') > -1) {

With your code, the expression in the first statement ifwill be true, even if the line does not contain a period. This means that the statement else ifwill never be executed.

+3
source

I want to convert almost any time format to the HH: mm: ss in javacript format

: http://www.datejs.com/

.

, , , Mark

+2

You use else ifone that requires all previous conditional blocks to be false.

Try the following:

    if(timeString.indexOf('.')){
        hoursEndIndex = timeString.indexOf('.');
        minutesStartIndex = timeString.indexOf('.') + 1;
    }
    if(timeString.length == 3){
        hoursEndIndex = 1;
        minutesStartIndex = 1;
    } else if(timeString.length == 4){
        hoursEndIndex = 2;
        minutesStartIndex = 2;
        return timeString.length;
    }
0
source

Perhaps you should use the captured groups instead of parsing the line:

var groups = regEx2.exec(timeString);
if(groups){
    var hours = groups[0];
    if(hours.length == 1){
        hours = '0' + hours;
    }
    var minutes = groups[1];
    return hours + ":" + minutes + ":00";
}
0
source

All Articles