Add AMAZON.DURATION to current time
Asked Answered
P

2

5

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?

Phone answered 5/3, 2016 at 5:22 Comment(0)
P
7

So I resolved this using the moment.js library. I was already using this to format and work with dates, and I discovered they also support durations.

The way I resolved this was by getting the current date, parsing the duration, and adding them together:

var now = moment();
var duration = moment.duration(myDurationString);
var futureDate = now.add(duration);

Then, I could format futureDate to be read back to the user and save it in the database.

Phone answered 6/3, 2016 at 3:46 Comment(0)
L
0

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"));
Lewandowski answered 14/7, 2019 at 23:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.