Search code examples
javascriptdayjs

Convert formatted time (HH:mm) to integer using dayjs


I am currently using the dayjs library and I am currently trying to convert a formatted time, such as '02:00' to an integer that represents the total minutes. In this case it would 120. I am trying to use dayjs duration plugin, but it appears the following does not work without passing in an integer. My code is as follows:

dayjs.duration('02:00').asMinutes()

this however returns NaN. If anyone is familiar with the dayjs library I would greatly appreciate any guidance.


Solution

  • You'll need to process your data, perhaps with regex. Duration does accept an object with explicit labels though to make this operation a bit easier.

    https://day.js.org/docs/en/durations/creating

    const timeString = "2:00";
    const h = timeString.match(/(\d{1,2}):\d+/)[1];
    const hInt = parseInt(h);
    console.log("Hours: " + hInt)
    
    const m = timeString.match(/\d{1,2}:(\d+)/)[1];
    const mInt = parseInt(m);
    console.log("Minutes: " + mInt);
    
    // dayjs.duration({ hours: hInt, minutes: mInt })

    EDIT: Per Amy's, this is more efficient and simpler:

    const [h, m] = "2:00".split(":").map( val => parseInt(val) );
    console.log("Hours: " + h)
    console.log("Minutes: " + m);
    
    // dayjs.duration({ hours: h, minutes: m})