0

I'm receiving from my database time like hh:mm:ss, and in javascript i would like to put the time like hh:mm this is my code

var time = '10:01:30';
console.log(time);
var res = formatTime(time);
console.log(res);

function formatTime(time) {
  var result = false, m;
  var re = /^\s*([01]?\d|2[0-3]):?([0-5]\d)\s*$/;
  if ((m = time.match(re))) {
    result = (m[1].length === 2 ? "" : "0") + m[1] + ":" + m[2];
    console.log(result);
  }
}

The function doesn't work well since i receive "false", any help?

Thanks

2
  • 1
    Made this a minimal reproducible example for you. Commented Jul 26, 2016 at 13:40
  • 1
    Don't see need for regex here at all. Consider working with an actual Date variable. This will have the side effect of also validating the input value, as the Data object will not be able to be successfully created if a valid format is not passed. Commented Jul 26, 2016 at 13:51

4 Answers 4

2

May be I am missing something in the question, but if you simply want to extract the hh:mm part from hh:mm:ss, then this should work:

// var time = "hh:mm:ss";
var time = "10:01:30";
var splitTime = time.trim().split(":"); // trim to remove any leading and trailing spaces
var formattedTime = splitTime[0] +":"+ splitTime[1];
console.log( formattedTime );

Sign up to request clarification or add additional context in comments.

3 Comments

Dont forget that their regex allows whitespace around the input, you might want to trim() your results
@Jamiec Thanks. But I have directly used the "10:01:30" string here. So, in this context, it should work fine. No?
but if the input was " 10:01:30 " (as the regex implies is possible) then you'll have those extra spaces in your formattedTime variable.
1

Couldn't you just do the following?:

    function formatTime(time) {
      var array = time.split(':');
      return array[0] + ':' + array[1];
    }

Comments

1

The other answer (using split) is undoubtably the easier way to do this.

However, if you're wondering why your regex was not matching, it is because your regular expression was looking for the first (hh) block, and then the second (mm) block, but was then expecting whitespace after that until the end of the line - no allowance for the ss part.

I changed this rather heavy-handedly to allow anything after the mm part until the end of the line. see below.

Also, if you're wondering why your formatTime function returns undefined its because you forgot to return result

var time = '10:01:30';
console.log(time);
var res = formatTime(time);
console.log(res);

function formatTime(time) {
  var result = false, m;
  var re = /^\s*([01]?\d|2[0-3]):?([0-5]\d).*$/;
  
  if ((m = time.match(re))) {
    result = (m[1].length === 2 ? "" : "0") + m[1] + ":" + m[2];
    console.log(result);
  }
  return result;
}

Comments

0

I would consider working with native Date object to do your formatting. This will do a few things for you:

  • Automatically validate the time value that is being input. No need for regex to do this. Either the input string is valid and the function works, or it is invalid and the function returns NaN.
  • Give you flexibility in how you work with the value. Need to convert time zones, convert to Unix timestamp, etc.? These are built in methods on Date object.
  • Gives flexibility on input values. You could potentially you other string input types here if needed as long as they can allow for instantiation of valid Date object. You need to modify regex to allow for multiple input types or anything like that.

Using this approach, example code might look like:

function stripSecondsFromTimeString(time) {
    // create data object representing current date
    // the date is not really important here other than allowing
    // you to format a fully valid Date object with your time fragment
    var day = new Date();
    var dateInput = day.toDateString() + ' ' + time;
    var date = new Date(dateInput);

    // validate we were able to get useful Date object
    if(isNaN(date.getHours())) {
        return NaN;
    }

    // log out some values so you can see how you might more fully work with Date object
    console.log(date.toString());
    console.log(date.getDate());
    console.log(date.getHours());
    console.log(date.getMinutes());

    // prepare to return string
    var hours = '' + date.getHours();
    if(hours.length === 1) {
        hours = '0' + hours;
    }
    var minutes = '' + date.getMinutes();
    if(minutes.length === 1) {
        minutes = '0' + minutes;
    }
    return hours + ':' + minutes;
 }

// Usage examples

// your input time fragment
var inputTime = '10:01:30';
var formattedTime = stripSecondsFromTimeString(inputTime);
console.log(formattedTime);

// example failure case
var invalidTime = 'foo';
console.log(stripSecondsFromTimeString(invalidTime));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.