DateTime数组间隔

时间:2018-02-20 19:44:41

标签: c# arrays datetime

我想创建一个DateTime数组,它从DateTime.now开始计算998步 每隔15分钟

我想要以下

假设时间是20:00

{DateTime.now; 19:45; 19:30; 19:15;...}

我从未直接与Arrays合作过,所以我在这里寻求帮助

1 个答案:

答案 0 :(得分:5)

我会使用LINQ与DateTime.AddMinutes结合使用。 LINQ使生成序列变得非常容易,然后将该序列转换为数组:

// Important: only call DateTime.Now once, so that all the values are
// consistent.
// Note that this will be the system local time - in many, many cases
// it's better to use UtcNow.
var now = DateTime.Now;
var times = Enumerable.Range(0, 998)
                      .Select(index => now.AddMinutes(index * -15))
                      .ToArray();

非LINQ方法首先会创建一个大小合适的数组,然后填充它:

// Same comments about DateTime.Now apply
var now = DateTime.Now;
var times = new DateTime[998];
for (int i = 0; i < times.Length; i++)
{
    times[i] = now.AddMinutes(i * -15);
}

我绝对更喜欢LINQ版..