简体   繁体   中英

Compare ISO 8601 periods in JavaScript

I am trying to compare ISO 8601 periods in JavaScript to see which period has a greater duration than the other. For example: P6M (6 months) is greater than PT10M (10 minutes).

I can't find anything out of the box which helps, perhaps you guys can help me achieve this.

There's nothing available OOTB using the native javascript Date object but Moment.js handles your ISO8601 durations just fine (and there's little point re-inventing the wheel here...)

eg the following demo prints: "6 months is greater than 10 minutes"

var d1 = moment.duration('P6M'),
    d2 = moment.duration('PT10M');

console.log(
    d1.humanize()
  + ( d1 < d2 ? ' is less than ' : ' is greater than ' )
  + d2.humanize()
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM