Add AMAZON.DURATION to current time

Viewed 824

I am writing an Alexa skill where I'd like to store records in a database with a future time. For example, if the user says "in two hours", I want to store the time two hours from now.

So far, I have discovered I can use an AMAZON.DURATION slot type to convert words like that into a duration, but I haven't yet figured out how I can add that to the current date.

The duration comes back like this: PT2H. The P indicates a duration, T indicates that it is time units, and the 2H is for 2 hours. I could parse this myself, but I was hoping there would be some built in function to do this?

2 Answers

Here's another way to do it without using any library.

function getDuration(amazon_duration) {
    let timelist = amazon_duration.match(/([S]?\d+)/gim);
    let duration = 0;
    if (timelist.length === 1) {
        duration = parseInt(timelist[0]) * 1;
    } else if (timelist.length === 2) {
        duration = (parseInt(timelist[0]) * 60) + (parseInt(timelist[1]) * 1);
    } else if (timelist.length === 3) {
        duration = (parseInt(timelist[0]) * 60 * 60) + (parseInt(timelist[1]) * 60) + (parseInt(timelist[2]) * 1);
    }

    return duration;
}

console.log(getDuration("PT1H10M25S"));
Related