C# 2.0 中的随机分钟
我如何向数据集中的列添加随机分钟,这是我的代码:
protected void btnUpdateTable_Click(object sender, EventArgs e)
{
foreach (DataRow dr in ds.Tables[0].Rows)
{
///check if column[logout] is null or empty, fill it
if(dr.IsNull("logout_time"))
{
///get the login colum datetime
/// add random datetime to it
if (!dr.IsNull("login_time"))
{
DateTime dt = Convert.ToDateTime(dr["login_time"]);
dt = dt.AddMinutes(?);/// "?"<--here I want to add random minutes
}
}
}
非常感谢任何帮助。
感谢大家的帮助,这是我的最终代码片段:
foreach (DataRow dr in ds.Tables[0].Rows)
{
///check if column[logout] is null or empty, fill it
if(dr.IsNull("logout_time"))
{
///get the login colum datetime
/// add random datetime to it
if (!dr.IsNull("login_time"))
{
DateTime dt = Convert.ToDateTime(dr["login_time"]);
Random rand = new Random();
//return random.Next(0, 59);
dt = dt.AddMinutes(rand.Next(0,59));
dt = dt.AddSeconds(rand.Next(0, 59));
dr["logout_time"] = dt;
}
}
}
Ho do I go about adding random minutes to column in dataset, here is my code:
protected void btnUpdateTable_Click(object sender, EventArgs e)
{
foreach (DataRow dr in ds.Tables[0].Rows)
{
///check if column[logout] is null or empty, fill it
if(dr.IsNull("logout_time"))
{
///get the login colum datetime
/// add random datetime to it
if (!dr.IsNull("login_time"))
{
DateTime dt = Convert.ToDateTime(dr["login_time"]);
dt = dt.AddMinutes(?);/// "?"<--here I want to add random minutes
}
}
}
Any help greatly appreciated.
Thank you all for the help, here my final Code snippet:
foreach (DataRow dr in ds.Tables[0].Rows)
{
///check if column[logout] is null or empty, fill it
if(dr.IsNull("logout_time"))
{
///get the login colum datetime
/// add random datetime to it
if (!dr.IsNull("login_time"))
{
DateTime dt = Convert.ToDateTime(dr["login_time"]);
Random rand = new Random();
//return random.Next(0, 59);
dt = dt.AddMinutes(rand.Next(0,59));
dt = dt.AddSeconds(rand.Next(0, 59));
dr["logout_time"] = dt;
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
尝试使用
随机
:Try using
Random
:假设您不希望 dt 对象移至下一小时(例如,您希望 8:00 到 8:59 之间的任何时间最多移至 8:59),我建议您进行以下操作变化:
Assuming you don't want your dt object to get moved into the next hour (e.g., you would want any time between 8:00 and 8:59 to get moved up to 8:59 at most), I would suggest making the following changes:
另请注意,彼此内的两个 if 语句可以优化为:
Also please note that two if-statements within each other can be optimized to:
您可以使用它:
正如评论指出的那样,您不需要为您希望创建的每个数字创建一个新的 Random 对象。 (实际上,你可能不应该)。
You can use this:
As a comment pointed out, you don't need to create a new Random object for every number you wish to create. (Actually, you probably shouldn't).