微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 在一天内完成几个小时的迭代

一个DateTime变量,例如:

DateTime testDate = new DateTime(2011,12,15,00,00);

如何在今天的每个小时实现一个foreach循环?

就像是:

foreach (int myHour in testDate.Date)
{

}

但是这种方式不能编译.

解决方法

循环24并不是一个好主意,因为这在25或23小时(时间变化,夏令时……)的日子里不起作用.

使用AddHour函数和目标日期.

DateTime testDate = new DateTime(2011,DateTimeKind.Local);
DateTime endDate = testDate.AddDays(1);

while (testDate.Date != endDate.Date)
{
    Console.WriteLine(testDate.ToString());
    testDate = testDate.AddHours(1);
}

更多信息

> MSDN – DateTimeKind Enumeration

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐