date method

String date({
  1. int start = 2000,
  2. int? end,
})

Returns random date in the YYYY-MM-DD format.

start is optional start year (default is 2000).

end is optional end year (default is current year).

Throws a RangeError if start or end is negative or start is greater than end.

Example:

Date().date(); // "2015-09-10"
Date().date(start: 2022, end: 2022); // "2022-08-20"

Implementation

String date({int start = 2000, int? end}) {
  final endYear = end ?? DateTime.now().year;

  if (start.isNegative || endYear.isNegative) {
    throw RangeError('start and end should be positive integers');
  }

  if (start > endYear) {
    throw RangeError.value(
      start,
      'start',
      'start cannot be greater than end',
    );
  }

  final random = Random(seed);
  final year = random.integer(min: start, max: endYear);
  final month = random.integer(min: 1, max: 12);
  final day = random.integer(
    min: 1,
    max: Util.daysInMonth(year: year, month: month),
  );
  final paddedMonth = month.toString().padLeft(2, '0');
  final paddedDay = day.toString().padLeft(2, '0');
  return '$year-$paddedMonth-$paddedDay';
}