clamp method
Returns this DateTime clamped to be in the range min
-max
.
The comparison is done using compareTo.
The arguments min
and max
must form a valid range where
min.compareTo(max) <= 0
.
Example:
var result = DateTime(2022, DateTime.october, 15).clamp(
min: DateTime(2022, DateTime.september, 1),
max: DateTime(2022, DateTime.september, 30),
); // DateTime(2022, DateTime.september, 30);
result = DateTime(2022, DateTime.august, 21).clamp(
min: DateTime(2022, DateTime.september, 15),
max: DateTime(2022, DateTime.september, 30),
); // DateTime(2022, DateTime.september, 15);
result = DateTime(2022, DateTime.september, 1).clamp(
min: DateTime(2022, DateTime.august, 1),
max: DateTime(2022, DateTime.september, 30),
); // DateTime(2022, DateTime.september, 1);
Implementation
DateTime clamp({DateTime? min, DateTime? max}) {
assert(
((min != null) && (max != null)) ? (min.isBefore(max) || (min == max)) : true,
'DateTime min has to be before or equal to max\n(min: $min - max: $max)',
);
if ((min != null) && compareTo(min).isNegative) {
return min;
} else if ((max != null) && max.compareTo(this).isNegative) {
return max;
}
return this;
}