normalize method
Returns a normalized copy of this.
This normalizes all units of time except for the days. For example, a period of "13 months, 50 days and 24 hours" will be normalized as "1 year, 1 month and 51 days".
Period(months: 13, days: 50, hours: 24).normalize(); // 1 year, 1 month, 51 days
Implementation
@useResult Period normalize() {
final totalMonths = years * 12 + months;
final normalizedMonths = totalMonths.remainder(12);
final normalizedYears = totalMonths ~/ 12;
var total =
days * Duration.microsecondsPerDay
+ hours * Duration.microsecondsPerHour
+ minutes * Duration.microsecondsPerMinute
+ seconds * Duration.microsecondsPerSecond
+ milliseconds * Duration.microsecondsPerMillisecond
+ microseconds;
final normalizedMicroseconds = total.remainder(1000);
final normalizedMilliseconds = (total ~/= 1000).remainder(1000);
final normalizedSeconds = (total ~/= 1000).remainder(60);
final normalizedMinutes = (total ~/= 60).remainder(60);
final normalizedHours = (total ~/= 60).remainder(24);
final normalizedDays = total ~/ 24;
return Period(
years: normalizedYears,
months: normalizedMonths,
days: normalizedDays,
hours: normalizedHours,
minutes: normalizedMinutes,
seconds: normalizedSeconds,
milliseconds: normalizedMilliseconds,
microseconds: normalizedMicroseconds,
);
}