I am creating ann app where a widget showing next birthday in days
like
final date1=DateTime(1980,12,25);
final date2=DateTime(2023,12,21);
date1 difference with today is 2 days
date2 difference with today is 361 days..(near abt)
i know date method ‘difference’ but it calculate year also,
here i want to ignore year
i have tried my way but looking not good code
int dateDifference(DateTime date) {
final today = DateTime.now();
//here replacing date's year with current year
DateTime dummyDate=DateTime(DateTime.now().year,date.month,date.day);
int difference = 0;
if (dummyDate.isBefore(today)) {
print('Yes it is before today');
//adding one year
dummyDate = DateTime(DateTime.now().year+1 , dummyDate.month, dummyDate.day);
difference = dummyDate.difference(today).inDays;
} else {
difference = dummyDate.difference(today).inDays;
}
return difference;
}
2
Answers
Check updated code that calculates the number of days until the next occurrence of a specific month and day, by comparing today’s date with the target date set to the current year, and adjusting to the next year if it has already passed.
You can’t just ignore the year. The number of days between two dates depends on the year; there is 1 day between February 28 and March 1 for 2023, but there are 2 days between them 2024.
Using
DateTime.difference().inDays
naively will give you unexpected results for locales that observe Daylight Saving Time if there is a DST event during that timespan. Also see: https://stackoverflow.com/a/71198806/If you want to compute the number of days until someone’s next birthday, what you have is already mostly right, but you should perform computations with UTC
DateTime
objects to avoid DST problems, and you could do some refactoring to avoid code duplication: