skip to Main Content

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


  1. 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.

       int dateDifference(DateTime date) {
          final today = DateTime.now();
          DateTime targetDate = DateTime(today.year, date.month, date.day);
    
          if (targetDate.isBefore(today)) {
            targetDate = DateTime(today.year + 1, date.month, date.day);
          }
        
          return targetDate.difference(today).inDays;
        }
    
    Login or Signup to reply.
    1. 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.

    2. 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:

    int daysTill(int month, int day) {
      var now = DateTime.now();
    
      // Discard time information.
      //
      // Also Perform all computations with UTC Datetime objets to avoid DST effects.
      var today = DateTime.utc(now.year, now.month, now.day);
      var next = DateTime.utc(today.year, month, day);
    
      if (next.isBefore(today)) {
        next = next.copyWith(year: today.year + 1);
      }
    
      return next.difference(today).inDays;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search