Reputation: 343
I Would have a dart questions.
print(DateTime(2020,03,12).add(new Duration(days: 17)));
print(DateTime(2020,03,12).add(new Duration(days: 18)));
Results:
2020-03-29 00:00:00.000
2020-03-30 01:00:00.000
I don't understand the second result. Why 01:00:00?
This is the result running on Flutter test and dartpad.dev online, although if I run it from flutter application it shows 00:00:00 correctly. Why?
print(DateTime(2019,03,12).add(new Duration(days: 17)));
print(DateTime(2019,03,12).add(new Duration(days: 18)));
shows:
2019-03-29 00:00:00.000
2019-03-30 00:00:00.000
print(DateTime(2021,03,12).add(new Duration(days: 17)));
print(DateTime(2021,03,12).add(new Duration(days: 18)));
shows:
2021-03-29 01:00:00.000
2021-03-30 01:00:00.000
Upvotes: 2
Views: 3490
Reputation: 445
The recommended way to add 1 day to a DateTime is like this:
DateTime other = ...;
DateTime nextDay = DateTime(other.year, other.month, other.day + 1, other.hour, other.minute)
You can write an extension method like this:
extension DateTimeExtension on DateTime {
DateTime addDays(int days) => DateTime(year, month, day + days, hour, minute);
}
Also works when day + days is greater than 31.
Upvotes: 1
Reputation: 31219
The reason is properly Daylight Saving Time since the add
method does only understand seconds as documented in the API and the Duration
are therefore converted to seconds before it is used:
Notice that the duration being added is actually 50 * 24 * 60 * 60 seconds. If the resulting DateTime has a different daylight saving offset than this, then the result won't have the same time-of-day as this, and may not even hit the calendar date 50 days later.
Be careful when working with dates in local time.
https://api.dart.dev/stable/2.7.2/dart-core/DateTime/add.html
Upvotes: 2