So I have generated a random date from two dates
JavaScript
x
6
1
var dateOfInterest = function randomDate(start, end) {
2
return new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime()));
3
}
4
5
randomDate(new Date(2012, 0, 1), new Date());
6
Now I need to collect the year of the random date generated with the code:
var yearOfInterest = dateOfInterest.getFullYear();
This does not work. I would appreciate the assistance. Thank you.
Advertisement
Answer
A function definition does not need the var
, just assign the function itself, then call it to receive the return value.
I’ve placed the getFullYear
in the function after creating a new Date
and changed the function name to a more describing one: getRandomYearBetweenDates
JavaScript
1
6
1
function getRandomYearBetweenDates(start, end) {
2
return new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime())).getFullYear();
3
}
4
5
const res = getRandomYearBetweenDates(new Date(2012, 0, 1), new Date());
6
console.log(res);