Convert minutes ( string ) to ISO 8601 duration format

Viewed 10069

I always store my minutes in a plain string format saying "90" for 90 minutes. I want to convert this to ISO 8601 duration format for schema.org standard.

E.g "90" should be converted to PT1H30M

1 Answers

In case whatever is going to read the interval isn't happy with values like PT90M, you can do something like this:

function MinutesToDuration(s) {
    var days = Math.floor(s / 1440);
    s = s - days * 1440;
    var hours = Math.floor(s / 60);
    s = s - hours * 60;

    var dur = "PT";
    if (days > 0) {dur += days + "D"};
    if (hours > 0) {dur += hours + "H"};
    dur += s + "M"

    return dur;
}

console.log(MinutesToDuration("0"));
console.log(MinutesToDuration("10"));
console.log(MinutesToDuration("90"));
console.log(MinutesToDuration(1000));
console.log(MinutesToDuration(10000));

Outputs:

PT0M
PT10M
PT1H30M
PT16H40M
PT6D22H40M

Related