Search code examples
javascriptnode.jsmomentjsdate-fns

Parse time '1hr 30m 4s' as time ahead in JavaScript


Let's say I have a string 1hr 30m 4s. How would I use Node.js to parse that string into (obviously) a time in the future from the date it was executed?

I have looked at the NPM packages date-fns and moment but they do not seem to cater to what I am looking for.

I guess you could do a RegExp?


Solution

  • You guess correctly. For future reference, you're likely to get better answers if you try to solve the problem yourself and post a minimal, complete and verifiable example of anything you have problems with.

    Coming on Stack Overflow and asking a question is more work than googling 'javascript regex' after all, for all involved.

    var date = new Date();
    var s = '1hr 30m 4s';
    var re = /((\d+)hr)?( (\d+)m)?( (\d+)s)?/m;
    var match = re.exec(s);
    if (match != null) {
        if (typeof(match[2]) !== 'undefined') {
            date.setHours( date.getHours() + parseInt(match[2]) );
        }
        if (typeof(match[4]) !== 'undefined') {
            date.setMinutes( date.getMinutes() + parseInt(match[4]) );
        }
        if (typeof(match[6]) !== 'undefined') {
            date.setSeconds( date.getSeconds() + parseInt(match[6]) );
        }
    }
    console.log(date);