How do I get a 4-digit year from fakerjs date.birthdate() when setting `max` and `min`

1k views Asked by At

I'm trying to use the community fakerjs library to get a random birthdate. I want it to be within the last 70 years at the latest. In my output, though, I keep getting years like 79 and 12 instead of 1979 or 2012. I can only get a 2-digit year.

let date = faker.date.birthdate({ max: 70, min: 1 });
// 0037-08-27T13:35:09.312Z
date.getFullYear()
// 37

.birthdate() by itself works fine, it's just when I use max and min that the problem shows up.

What am I doing wrong?

1

There are 1 answers

0
Mixchange On

There's no bug, I just wasn't reading the docs correctly. I assumed faker.date.birthdate({ max: 70, min: 1 }) would understand 70 and 1 to be ages, but the method by default thinks they're actually years, so it's imagining that I want anything between the year 0001 and the year 0070.

I needed to add mode: 'age' to the options:

let date = faker.date.birthdate({ max: 70, min: 1, mode: 'age' });
// 1965-02-05T20:58:06.207Z
date.getFullYear()
// 1965

By default, mode is set to year.