Elegant method to generate array of random dates within two dates

会有一股神秘感。 提交于 2019-11-27 06:28:52
Tomasz Nurkiewicz

Maybe I am missing something, but isn't this it?

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

randomDate(new Date(2012, 0, 1), new Date())
Demven Weir
new Date(+(new Date()) - Math.floor(Math.random()*10000000000))

You can convert the boundary dates to integers (Date.getTime()) and then use Math.random() to generate your random dates within given boundaries. Then go back to Date objects with Date.setTime().

Using Moment.js && @Demven Weir's answer to get a string value like "03/02/1975".

moment(new Date(+(new Date()) - Math.floor(Math.random()*10000000000)))
.format('MM/DD/YYYY');

NOTE: Keep adding a zero at a time to increase the span of years produced.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!