How to parse a duration string into seconds with Javascript?

后端 未结 5 1297
闹比i
闹比i 2020-12-28 23:42

I\'m trying to parse a user input string for duration (into seconds) with Javascript.

Here are some example inputs that I\'d like to be able to deal with:

5条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-12-29 00:29

    A more general version of the accepted answer that accepts months and seconds as well.

    const getSeconds = str => {
        let seconds = 0;
        let months = str.match(/(\d+)\s*M/);
        let days = str.match(/(\d+)\s*D/);
        let hours = str.match(/(\d+)\s*h/);
        let minutes = str.match(/(\d+)\s*m/);
        let secs = str.match(/(\d+)\s*s/);
        if (months) { seconds += parseInt(months[1])*86400*30; }
        if (days) { seconds += parseInt(days[1])*86400; }
        if (hours) { seconds += parseInt(hours[1])*3600; }
        if (minutes) { seconds += parseInt(minutes[1])*60; }
        if (secs) { seconds += parseInt(secs[1]); }
        return seconds;
    };

提交回复
热议问题