cancel
Showing results forย 
Search instead forย 
Did you mean:ย 

Convert time into mins

peter
New Contributor III

Hi

I have a JSON field that contains elapsed time in the form 2 hours 17 Minutes 35 Seconds. What is the easiest way to convert this to decimal mins?

In the example above it would be 2 * 60 + 17 = 137 (ignore the seconds)

The string will not always contains the hours or mins, i.e.
2 hours 35 seconds or
18 minutes 25 seconds

1 ACCEPTED SOLUTION

koryknick
Employee
Employee

Try this:
$timestr.split(โ€™ ').reduce((accum,curVal,curIdx,array) => accum + (curIdx % 2 == 0 ? parseInt(curVal) * (array[curIdx+1] == โ€œhoursโ€ ? 60 : (array[curIdx+1] == โ€œminutesโ€ ? 1 : 0)): 0), 0)

Explanation of solution:

$timestr is the input string you provided, ex: 2 hours 35 seconds
.split(โ€™ ') converts the string to an array of the words: [โ€œ2โ€, โ€œhoursโ€, โ€œ35โ€, โ€œsecondsโ€]
.reduce is an Array function that letโ€™s you collapse the array to a scalar element (See Array Functions - reduce)
In the reduce, weโ€™re examining each array element, parsing every other element as an integer and multiplying the value appropriately for hours, adding minutes, and ignoring seconds

As with any programming tool, there are multiple ways to achieve the desired result, but this is the first I thought of and I believes accomplishes what you want.

View solution in original post

4 REPLIES 4

koryknick
Employee
Employee

Try this:
$timestr.split(โ€™ ').reduce((accum,curVal,curIdx,array) => accum + (curIdx % 2 == 0 ? parseInt(curVal) * (array[curIdx+1] == โ€œhoursโ€ ? 60 : (array[curIdx+1] == โ€œminutesโ€ ? 1 : 0)): 0), 0)

Explanation of solution:

$timestr is the input string you provided, ex: 2 hours 35 seconds
.split(โ€™ ') converts the string to an array of the words: [โ€œ2โ€, โ€œhoursโ€, โ€œ35โ€, โ€œsecondsโ€]
.reduce is an Array function that letโ€™s you collapse the array to a scalar element (See Array Functions - reduce)
In the reduce, weโ€™re examining each array element, parsing every other element as an integer and multiplying the value appropriately for hours, adding minutes, and ignoring seconds

As with any programming tool, there are multiple ways to achieve the desired result, but this is the first I thought of and I believes accomplishes what you want.

peter
New Contributor III

Thanks for the super quick response.

I get this error witht he expression above.
Could not compile expression: $duration.split(โ€™ ').reduce((a โ€ฆ (Reason: Invalid token: โ€˜โ€™โ€™ for expression: $duration.split(โ€™ ').reduce((a โ€ฆ; Resolution: Please check expression syntax)

koryknick
Employee
Employee

You may need to re-type the quotes (both single quotes and double quotes). Sometimes Windows likes to replace them with Unicode characters that Javascript doesnโ€™t like.

peter
New Contributor III

That was it.

Super thanks