Clamp date when jumping from leap to common year
diff --git a/lib/clock.dart b/lib/clock.dart
index e2b4ea6..4ddfe78 100644
--- a/lib/clock.dart
+++ b/lib/clock.dart
@@ -179,10 +179,12 @@
/// Return the point in time [years] ago on the same date.
DateTime yearsAgo(int years) {
var time = now();
+ var y = time.year - years;
+ var d = time.day.clamp(1, _daysInMonth(y, time.month));
return new DateTime(
- time.year - years,
+ y,
time.month,
- time.day,
+ d,
time.hour,
time.minute,
time.second,
diff --git a/test/clock_test.dart b/test/clock_test.dart
index d14b5cd..0fc44a1 100644
--- a/test/clock_test.dart
+++ b/test/clock_test.dart
@@ -186,6 +186,22 @@
expectDate(from(2003, 12, 31).monthsFromNow(2), 2004, 2, 29);
});
+ test("should go from 2004-02-29 to 2003-02-28 by year", () {
+ expectDate(from(2004, 2, 29).yearsAgo(1), 2003, 2, 28);
+ });
+
+ test("should go from 2004-02-29 to 2003-02-28 by month", () {
+ expectDate(from(2004, 2, 29).monthsAgo(12), 2003, 2, 28);
+ });
+
+ test("should go from 2004-02-29 to 2005-02-28 by year", () {
+ expectDate(from(2004, 2, 29).yearsFromNow(1), 2005, 2, 28);
+ });
+
+ test("should go from 2004-02-29 to 2005-02-28 by month", () {
+ expectDate(from(2004, 2, 29).monthsFromNow(12), 2005, 2, 28);
+ });
+
test("should return time years ago on the same date", () {
expectDate(subject.yearsAgo(1), 2012, 1, 1); // leap year
expectDate(subject.yearsAgo(2), 2011, 1, 1);