Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript time conversion regexp

I have a method using regular expressions in .Net to convert time from e.g. "1h 20m" format to double. Here is it.

public static double? GetTaskHours(this string tmpHours) {
  Double taskHours = 0;
  if (!string.IsNullOrEmpty(tmpHours) && !double.TryParse(tmpHours, out taskHours)) {
    var match = Regex.Match(tmpHours, @"^(?=\d)((?<hours>\d+)(h|:))?\s*((?<minutes>\d+)m?)?$", RegexOptions.ExplicitCapture);
    if (match.Success) {
      int hours;
      int.TryParse(match.Groups["hours"].Value, out hours);
      int minutes;
      int.TryParse(match.Groups["minutes"].Value, out minutes);
      taskHours = (double)hours + (double)minutes / 60;
    }
  }
  return Math.Round(taskHours, 3);
}

Now I need the same using Javascript. I tried to convert the regex according to http://www.w3schools.com/jsref/jsref_regexp_nfollow.asp but all my atempts failed. I'm very poor in regular expressions.

Here is my JS attempt.

function getHours(value) {
  var myArray = value.match(/^(?=\d)((\d+)(h|:))?\s*((\d+)m?)?$/g);
  var hours = myArray[2];
  var minutes = myArray[5];
  return Number(hours) + Number(minutes) / 60;
}

Is it correct?
Can you please show me the way?

Regards, Dmitry.

like image 703
StNickolas Avatar asked Mar 26 '26 09:03

StNickolas


1 Answers

The String.match method will return only an array of the complete matches, not of any groups. Use the Regex.exec method to get all the groups:

function getHours(value) {
    var myArray = (/^((\d+)(h|:))?\s*((\d+)m?)?$/g).exec(value);
    var hours = myArray[2];
    var minutes = myArray[5];
    return Number(hours) + Number(minutes) / 60;
}
like image 70
Gareth Cornish Avatar answered Mar 27 '26 22:03

Gareth Cornish