Generate random date between two dates and times in Javascript

前端 未结 7 2364
别那么骄傲
别那么骄傲 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:47

    Here is a good one if you just want simple dates such as: ('12/13/2013', '01/26/2011')

    function randomDate(date1, date2){
        function randomValueBetween(min, max) {
          return Math.random() * (max - min) + min;
        }
        var date1 = date1 || '01-01-1970'
        var date2 = date2 || new Date().toLocaleDateString()
        date1 = new Date(date1).getTime()
        date2 = new Date(date2).getTime()
        if( date1>date2){
            return new Date(randomValueBetween(date2,date1)).toLocaleDateString()   
        } else{
            return new Date(randomValueBetween(date1, date2)).toLocaleDateString()  
    
        }
    }
    
    randomDate('02/13/2013', '01/01/2000')
    "1/31/2009"
    randomDate()
    "6/14/2001"
    
    0 讨论(0)
提交回复
热议问题