So I have generated a random date from two dates
var dateOfInterest = function randomDate(start, end) { return new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime())); } randomDate(new Date(2012, 0, 1), new Date());
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
function getRandomYearBetweenDates(start, end) { return new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime())).getFullYear(); } const res = getRandomYearBetweenDates(new Date(2012, 0, 1), new Date()); console.log(res);