Generate random date between two dates and times in Javascript

前端 未结 7 2420
别那么骄傲
别那么骄傲 2020-12-14 08:06

I want to generate a random date between two dates and between two times in javascript. For instance I want to generate a random date (between 8 am and 6 pm) between today a

7条回答
  •  鱼传尺愫
    2020-12-14 08:41

    Try this:

    function getRandomDate(from, to) {
        from = from.getTime();
        to = to.getTime();
        return new Date(from + Math.random() * (to - from));
    }
    

    When creating a date you can set a time also:

    var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);
    

    If you want the date to be, for example, between 8 am and 6 pm, simply set a random time after you get a random date.

    So in this case the function would look like this:

    function getRandomDate(fromDate, toDate, fromTime, toTime) {
        fromDate = fromDate.getTime();
        toDate = toDate.getTime();
        fromTime.setFullYear(1970,0,1); //reset the date
        toTime.setFullYear(1970,0,1); //because we only want a time here
        fromTime = fromTime.getTime();
        toTime = toTime.getTime();
        randomDate = new Date(fromDate + Math.random() * (toDate - fromDate));
        randomTime = new Date(fromTime + Math.random() * (toTime - fromTime));
        randomDate.setHours(randomTime.getHours());
        randomDate.setMinutes(randomTime.getMinutes());
        randomDate.setSeconds(randomTime.getSeconds());
    }
    

提交回复
热议问题