C#中的随机日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/194863/
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-03 17:32:42  来源:igfitidea点击:

Random date in C#

c#datetimerandomdate

提问by Judah Gabriel Himango

I'm looking for some succinct, modern C# code to generate a random date between Jan 1 1995 and the current date.

我正在寻找一些简洁的现代 C# 代码来生成 1995 年 1 月 1 日和当前日期之间的随机日期。

I'm thinking some solution that utilizes Enumerable.Range somehow may make this more succinct.

我在想一些利用 Enumerable.Range 的解决方案可能会使这更简洁。

采纳答案by Joel Coehoorn

private Random gen = new Random();
DateTime RandomDay()
{
    DateTime start = new DateTime(1995, 1, 1);
    int range = (DateTime.Today - start).Days;           
    return start.AddDays(gen.Next(range));
}

For better performance if this will be called repeatedly, create the startand gen(and maybe even range) variables outsideof the function.

如果这将被重复调用,为了获得更好的性能,请在函数外部创建startgen(甚至可能是range)变量。

回答by Gabriele D'Antona

Start with a fixed date object (Jan 1, 1995), and add a random number of days with AddDays (obviusly, pay attention not surpassing the current date).

从固定日期对象(1995 年 1 月 1 日)开始,并使用 AddDays 添加随机天数(显然,注意不要超过当前日期)。

回答by JaredPar

This is in slight response to Joel's comment about making a slighly more optimized version. Instead of returning a random date directly, why not return a generator function which can be called repeatedly to create a random date.

这是对 Joel 关于制作稍微更优化版本的评论的轻微回应。与其直接返回一个随机日期,不如返回一个可以重复调用的生成器函数来创建一个随机日期。

Func<DateTime> RandomDayFunc()
{
    DateTime start = new DateTime(1995, 1, 1); 
    Random gen = new Random(); 
    int range = ((TimeSpan)(DateTime.Today - start)).Days; 
    return () => start.AddDays(gen.Next(range));
}

回答by James Curran

Well, if you gonna present alternate optimization, we can also go for an iterator:

好吧,如果您要展示替代优化,我们也可以使用迭代器:

 static IEnumerable<DateTime> RandomDay()
 {
    DateTime start = new DateTime(1995, 1, 1);
    Random gen = new Random();
    int range = ((TimeSpan)(DateTime.Today - start)).Days;
    while (true)
        yield return  start.AddDays(gen.Next(range));        
}

you could use it like this:

你可以这样使用它:

int i=0;
foreach(DateTime dt in RandomDay())
{
    Console.WriteLine(dt);
    if (++i == 10)
        break;
}

回答by prespic

I have taken @Joel Coehoorn answer and made the changes he adviced - put the variable out of the method and put all in class. Plus now the time is random too. Here is the result.

我已经接受了@Joel Coehoorn 的回答并进行了他建议的更改 - 将变量从方法中取出并全部放入类中。加上现在时间也是随机的。这是结果。

class RandomDateTime
{
    DateTime start;
    Random gen;
    int range;

    public RandomDateTime()
    {
        start = new DateTime(1995, 1, 1);
        gen = new Random();
        range = (DateTime.Today - start).Days;
    }

    public DateTime Next()
    {
        return start.AddDays(gen.Next(range)).AddHours(gen.Next(0,24)).AddMinutes(gen.Next(0,60)).AddSeconds(gen.Next(0,60));
    }
}

And example how to use to write 100 random DateTimes to console:

以及如何使用将 100 个随机日期时间写入控制台的示例:

RandomDateTime date = new RandomDateTime();
for (int i = 0; i < 100; i++)
{
    Console.WriteLine(date.Next());
}

回答by Hamit Gündogdu

I am a bit late in to the game, but here is one solution which works fine:

我进入游戏有点晚了,但这里有一个工作正常的解决方案:

    void Main()
    {
        var dateResult = GetRandomDates(new DateTime(1995, 1, 1), DateTime.UtcNow, 100);
        foreach (var r in dateResult)
            Console.WriteLine(r);
    }

    public static IList<DateTime> GetRandomDates(DateTime startDate, DateTime maxDate, int range)
    {
        var randomResult = GetRandomNumbers(range).ToArray();

        var calculationValue = maxDate.Subtract(startDate).TotalMinutes / int.MaxValue;
        var dateResults = randomResult.Select(s => startDate.AddMinutes(s * calculationValue)).ToList();
        return dateResults;
    }

    public static IEnumerable<int> GetRandomNumbers(int size)
    {
        var data = new byte[4];
        using (var rng = new System.Security.Cryptography.RNGCryptoServiceProvider(data))
        {
            for (int i = 0; i < size; i++)
            {
                rng.GetBytes(data);

                var value = BitConverter.ToInt32(data, 0);
                yield return value < 0 ? value * -1 : value;
            }
        }
    }

回答by BernardV

Small method that returns a random date as string, based on some simple input parameters. Built based on variations from the above answers:

基于一些简单的输入参数,以字符串形式返回随机日期的小方法。基于上述答案的变化而构建:

public string RandomDate(int startYear = 1960, string outputDateFormat = "yyyy-MM-dd")
{
   DateTime start = new DateTime(startYear, 1, 1);
   Random gen = new Random(Guid.NewGuid().GetHashCode());
   int range = (DateTime.Today - start).Days;
   return start.AddDays(gen.Next(range)).ToString(outputDateFormat);
}