generateDate static method

String generateDate({
  1. DateTime? maxDate,
  2. DateTime? minDate,
})

Generates a random date of birth (YYMMDD) within a specified date range.

The maxDate and minDate parameters define the date range for generating the birth date. Returns a string representing the generated date of birth.

Implementation

static String generateDate({DateTime? maxDate, DateTime? minDate}) {
  final fromDate = maxDate ?? DateTime(1920);
  final toDate = minDate ?? DateTime.now();

  if (fromDate.isAfter(toDate) == true ||
      fromDate.isAtSameMomentAs(toDate) == true) {
    throw "Invalid date range: maxDate should not be after minDate.";
  }

  final timeBetweenDates =
      toDate.subtract(Duration(days: toDate.difference(fromDate).inDays));

  final int daysBetweenDates = toDate.difference(fromDate).inDays;

  final int randomNumberOfDays = Random().nextInt(daysBetweenDates);
  final DateTime randomDate =
      timeBetweenDates.add(Duration(days: randomNumberOfDays));
  return DateFormat('yyMMdd').format(randomDate);
}