Elegant method to generate array of random dates within two dates

前端 未结 4 1759
夕颜
夕颜 2020-11-30 21:17

I have a datepicker where I show two months and I want to randomly choose 3 dates in each visible month

  $(\'.date\').datepicker({
    minDate: new Date(),         


        
相关标签:
4条回答
  • 2020-11-30 21:32

    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())
    
    0 讨论(0)
  • 2020-11-30 21:34
    new Date(+(new Date()) - Math.floor(Math.random()*10000000000))
    
    0 讨论(0)
  • 2020-11-30 21:37

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

    0 讨论(0)
  • 2020-11-30 21:47

    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.

    0 讨论(0)
提交回复
热议问题