Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Collecting random year from Random Date

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();

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This does not work. I would appreciate the assistance. Thank you.

>Solution :

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

function randomDate(start, end) {
    return new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime())).getFullYear();
}

const res = randomDate(new Date(2012, 0, 1), new Date());
console.log(res);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading