在两个日期时间之间获取随机DateTime的最佳实践是什么? [英] What's the best practice for getting a random DateTime between two date-times?

查看:105
本文介绍了在两个日期时间之间获取随机DateTime的最佳实践是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将一个简单的DateTime数据字段的值随机化.

I'm trying to randomize the value for a simple DateTime data field.

我希望获得两个日期/时间之间的随机日期/时间(例如,最小日期/时间和最大日期/时间).

I wish to get a random date/time between two date/times (e.g. min date/time and max date/time).

所以让我们想象一下我在一个随机的日期/时间之后

So lets imagine I'm after a random date/time between

1/1/2000 10:00:00am1/1/2000 5:00:00pm.

此外,此代码还将在for循环中使用,其中包含100个项目……这意味着所有100个项目在最小/最大日期/时间段之间将具有随机的日期/时间.

Also, this code will be used in a for loop, with 100 items ... meaning all 100 items will have random date/times between the min/max date/time period.

有什么想法吗?

推荐答案

您可以尝试使用:

var randomTest = new Random();

TimeSpan timeSpan = endDate - startDate;
TimeSpan newSpan = new TimeSpan(0, randomTest.Next(0, (int)timeSpan.TotalMinutes), 0);
DateTime newDate = startDate + newSpan;

这将为您提供不同的时间.如果要100个(或大于1的任何东西)DateTime,则只需创建一次Random对象. Random 上的 MSDN页面详细说明了为什么创建快速连续几个Random对象是一个坏主意.

This will give you different times down to the minute. If you want 100 (or any thing more than 1) DateTimes then only create the Random object once. The MSDN page on Random explains in detail why creating several Random objects in quick succession is a bad idea.

使用不同的TimeSpan构造函数将为您提供不同的粒度.从 TimeSpan构造函数MSDN :

Using a different TimeSpan constructor will give you different granularity. From the TimeSpan constructor MSDN:

TimeSpan(Int64)将新的TimeSpan初始化为指定的刻度数.
TimeSpan(Int32,Int32,Int32)将新的TimeSpan初始化为指定的小时,分​​钟和秒数.
TimeSpan(Int32,Int32,Int32,Int32)将新的TimeSpan初始化为指定的 天,小时,分钟和秒.
TimeSpan(Int32,Int32,Int32,Int32,Int32)将新的TimeSpan初始化为指定的天数,小时数,分钟数,秒数和毫秒数.

TimeSpan(Int64) Initializes a new TimeSpan to the specified number of ticks.
TimeSpan(Int32, Int32, Int32) Initializes a new TimeSpan to a specified number of hours, minutes, and seconds.
TimeSpan(Int32, Int32, Int32, Int32) Initializes a new TimeSpan to a specified number of days, hours, minutes, and seconds.
TimeSpan(Int32, Int32, Int32, Int32, Int32) Initializes a new TimeSpan to a specified number of days, hours, minutes, seconds, and milliseconds.

这篇关于在两个日期时间之间获取随机DateTime的最佳实践是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆