Skip to content

Commit

Permalink
fix: consider the year when rounded
Browse files Browse the repository at this point in the history
  • Loading branch information
g1eny0ung committed Feb 3, 2022
1 parent d68720e commit 95282a1
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 8 deletions.
32 changes: 29 additions & 3 deletions lib/src/day.dart
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ class Day {
/// returns a new [Day] instance.
Day clone() => Day.fromDateTime(_time);

Day _cloneAndSetSingleValue(key, val) {
Day _cloneAndSetSingleValue(String key, val) {
final d = clone();

d.setValue(key, val);
Expand All @@ -137,6 +137,17 @@ class Day {
return d;
}

Day _cloneAndSetMultipleValues(Map<String, int> values) {
final d = clone();

values.forEach((key, value) {
d.setValue(key, value);
});
d.finished();

return d;
}

/// Gets or sets the year of this [Day].
///
/// When setting a new year, it will return a new [Day] instance with the new year.
Expand Down Expand Up @@ -334,7 +345,22 @@ class Day {
return d;
} else {
if (unit == Unit.y || unit == 'y') {
return _cloneAndSetSingleValue(Unit.y, year() + val);
final currentYear = year() + val;

if (rounded) {
final currentMonth = month();

// First determines if the month is February to avoid over-checking
if (currentMonth == 2 &&
u.isDateOverflow(currentYear, currentMonth, date())) {
return _cloneAndSetMultipleValues({
Unit.y: currentYear,
Unit.d: u.daysInMonth(currentYear, currentMonth),
});
}
}

return _cloneAndSetSingleValue(Unit.y, currentYear);
} else if (unit == Unit.m || unit == 'M') {
final d = clone();

Expand All @@ -352,7 +378,7 @@ class Day {

if (rounded) {
final currentYear = d.year();
var currentMonth = d.month();
final currentMonth = d.month();

if (u.isDateOverflow(currentYear, currentMonth, d.date())) {
d.setValue(Unit.d, u.daysInMonth(currentYear, currentMonth));
Expand Down
17 changes: 12 additions & 5 deletions test/day_add_round_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,19 @@ import 'package:test/test.dart';
import 'package:day/day.dart';

void main() {
final d = Day.fromString('2022-03-31T15:52:50.000Z');
test('.addRound(1, \'M\') returns a date not exceeding the current month',
() {
final d = Day.fromString('2022-03-31T15:52:50.000Z').addRound(1, 'M')!;

test('.addRound() returns a date not exceeding the current month', () {
final dClone = d.addRound(1, 'M')!;
expect(d.month(), equals(4));
expect(d.date(), 30);
});

test('.addRound(1, \'y\') returns a date not exceeding the current month',
() {
final d = Day.fromString('2020-02-29T15:52:50.000Z').addRound(1, 'y')!;

expect(dClone.month(), equals(4));
expect(dClone.date(), 30);
expect(d.month(), equals(2));
expect(d.date(), 28);
});
}

0 comments on commit 95282a1

Please sign in to comment.