Enough-Software / enough_icalendar

iCalendar library to parse, generate and respond to iCal / ics invites. Fully compliant with RFC 5545 (iCalendar) and RFC 5546 (iTIP).
Mozilla Public License 2.0
10 stars 9 forks source link

How can I convert Dart `Duration` to `IsoDuration`? #11

Closed liplum closed 9 months ago

liplum commented 11 months ago

Help wanted

I don't really know IsoDuration format and how to convert it to Dart Duration. So I was looking for a Duration.toIsoDuration() function in the source code, but I didn't.

Would you like to provide an extension function, a named/factory constructor, or a static function to convert Duration object to IsoDuration object? That would be very helpful.

liplum commented 11 months ago

I made this.

extension DurationX on Duration {
  IsoDuration toIso() {
    final isNegativeDuration = isNegative;

    // Convert the absolute value of each duration component
    final years = inDays ~/ 365;
    final months = (inDays % 365) ~/ 30;
    final weeks = ((inDays % 365) % 30) ~/ 7;
    final days = ((inDays % 365) % 30) % 7;
    final hours = inHours % 24;
    final minutes = inMinutes % 60;
    final seconds = inSeconds % 60;

    return IsoDuration(
      years: years,
      months: months,
      weeks: weeks,
      days: days,
      hours: hours,
      minutes: minutes,
      seconds: seconds,
      isNegativeDuration: isNegativeDuration,
    );
  }
}
robert-virkus commented 9 months ago

Thanks a lot, I added your extension in v0.16.0!