Random Date Generator

Valid dates only: February never gets a 30th, and leap years are counted properly, which matters the moment the output reaches a date parser.

Month lengths and leap years

The common bug in a naive date generator is picking a day between 1 and 31 regardless of month, which produces 31 February about once every forty draws. That value looks fine in a list and fails the moment it reaches a date parser, which is exactly when you least want to be debugging your test data. This generator looks up the real length of the chosen month in the chosen year before picking a day, so leap years get their 29 February and non-leap years do not. Every date it produces is a date that exists.

Format is a test case in itself

The three output formats are not just presentation. ISO is unambiguous, sorts correctly as a string, and is what an API should be given. The long form spells the month, which removes the ambiguity between day-first and month-first conventions for human readers. The US numeric form is the ambiguous one, 03/04 is March fourth or the third of April depending entirely on the reader, and that is precisely why it belongs in a test set. Feeding all three through your parser is how you find out whether it assumes a locale.

Frequently asked questions

Can it generate an invalid date like 31 February?

No. The real length of the chosen month in the chosen year is looked up before a day is picked, so leap years are handled correctly.

Which format should I use for an API fixture?

ISO. It is unambiguous, sorts correctly as a plain string, and does not depend on the reader knowing whether day or month comes first.

Can I generate dates in the past only?

Yes. Set both year bounds to years that have already passed and every result falls inside that range.