Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert minutes ( string ) to ISO 8601 duration format

Tags:

javascript

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

like image 311
Joelgullander Avatar asked Oct 26 '25 13:10

Joelgullander


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

like image 158
Andrew Morton Avatar answered Oct 29 '25 04:10

Andrew Morton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!