Forum Discussion

peter's avatar
peter
New Contributor III
4 years ago
Solved

Convert time into mins

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...
  • koryknick's avatar
    4 years ago

    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.