Javascript 在Javascript中的两个日期和时间之间生成随机日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31378526/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 06:37:24  来源:igfitidea点击:

Generate random date between two dates and times in Javascript

javascriptdate

提问by Yanki Twizzy

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 and next tomorrow. I have tried a whole bunch of things but none of them work so I won't be pasting any code since it does not work. Has anyone done something similar

我想在两个日期之间和 javascript 中的两次之间生成一个随机日期。例如,我想在今天和明天之间生成一个随机日期(上午 8 点到下午 6 点之间)。我已经尝试了很多东西,但没有一个起作用,所以我不会粘贴任何代码,因为它不起作用。有没有人做过类似的事情

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

The code I am using for generating random dates is posted above

我用于生成随机日期的代码发布在上面

回答by Peter Olson

I think I understand what you are after. This will return a random date between startand end, with a random hour between startHourand endHour(which should be values in the range 0-23).

我想我明白你在追求什么。这将返回一个随机日期之间startend,与之间的随机小时startHourendHour(其应该在的范围内的值0-23)。

function randomDate(start, end, startHour, endHour) {
  var date = new Date(+start + Math.random() * (end - start));
  var hour = startHour + Math.random() * (endHour - startHour) | 0;
  date.setHours(hour);
  return date;
}

回答by Barrard

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

如果您只想要简单的日期,这是一个很好的方法,例如:('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"

回答by user1136881

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.

例如,如果您希望日期在上午 8 点到下午 6 点之间,只需在获得随机日期后设置一个随机时间即可。

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

回答by Pravin

try this:

尝试这个:

var yourRandomGenerator=function(rangeOfDays,startHour,hourRange){
    var today = new Date(Date.now());
    return new Date(today.getYear()+1900,today.getMonth(), today.getDate()+Math.random() *rangeOfDays, Math.random()*hourRange + startHour, Math.random()*60)
}

console.log(yourRandomGenerator(2,8,2));

here's a working fiddle.

是一个工作小提琴。

回答by benams

You can use JS ability to convert a Date to an integer timestamp

您可以使用 JS 功能将日期转换为整数时间戳

Here is a simple working JSfiddle:

这是一个简单的工作JSfiddle

function randomTime(start, end) {
    var diff =  end.getTime() - start.getTime();
    var new_diff = diff * Math.random();
    var date = new Date(start.getTime() + new_diff);
    return date;
}

回答by Oliver Dixon

Since everyone is doing TypeScript now. Here's a more modern example with an example of how to use it.

因为现在每个人都在做 TypeScript。这是一个更现代的示例,其中包含如何使用它的示例。

const generateRandomDOB = (): string => {
    const random = getRandomDate(new Date('1950-02-12T01:57:45.271Z'), new Date('2001-02-12T01:57:45.271Z'))
    return random.toISOString();
}

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