使用 DateTimePicker 获取两个选定日期之间的天数

发布于 2024-12-17 22:28:00 字数 267 浏览 0 评论 0原文

我正在使用两个 dateTimePicker,假设我在第一个上选择了 11-11-2011,在最后一个上选择了 17-11-2011。现在我想获取这两个日期之间的日期。我只想得到这样的结果:

11-11-2011 
12-11-2011 
13-11-2011 
14-11-2011 
15-11-2011 
16-11-2011 
17-11-2011 

我该怎么做?

我试图从詹姆斯·希尔的问题中找出答案,但无法弄清楚。 谢谢,

I am using two dateTimePicker's, and lets say I've chosen 11-11-2011 on the first, and 17-11-2011 on the last. Now I want to get the dates between these two dates. I just want to get a result like this:

11-11-2011 
12-11-2011 
13-11-2011 
14-11-2011 
15-11-2011 
16-11-2011 
17-11-2011 

How am I supposed to do this ?

I've tried to make it out from the question by James Hill, but couldnt figure it out.
Thanks,

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

小红帽 2024-12-24 22:28:01

尝试一下:

DateTime start = DateTime.Today;
DateTime end = DateTime.Today.AddDays(7);

for (DateTime current = start; current <= end; current = current.AddDays(1))
{
    Console.WriteLine(current);
}

我喜欢使用 for 循环来处理这类事情,因为我经常在现代 .NET 项目中错过它们:)

一个可能的辅助方法:

static IEnumerable<DateTime> GetRange(DateTime start, DateTime end)
{
    for (DateTime current = start; current <= end; current = current.AddDays(1))
    {
        yield return current;
    }
}

重要如果您有时间 -部分,条件必须更改为 current.Date <= end.Date

编辑 更改以便包含边界,我之前只提供了日期 -之间。

Give this a try:

DateTime start = DateTime.Today;
DateTime end = DateTime.Today.AddDays(7);

for (DateTime current = start; current <= end; current = current.AddDays(1))
{
    Console.WriteLine(current);
}

I like using a for-loop for this kind of stuff, since I do often miss them in modern .NET projects :)

A possible helper method:

static IEnumerable<DateTime> GetRange(DateTime start, DateTime end)
{
    for (DateTime current = start; current <= end; current = current.AddDays(1))
    {
        yield return current;
    }
}

Important If you have a time-portion as well, the condition must be changed to current.Date <= end.Date

Edit Changed so that the boundaries are included, I previously only provided the dates in-between.

苦妄 2024-12-24 22:28:01

此代码也应该有效:

var timeSpan = (last.Value - first.Value);

var result = new List<DateTime>()
for (int i = 0; i < timeSpan.Days; i++)
{
    a.Add (first.AddDays (i));
}
return result;

This code should work too:

var timeSpan = (last.Value - first.Value);

var result = new List<DateTime>()
for (int i = 0; i < timeSpan.Days; i++)
{
    a.Add (first.AddDays (i));
}
return result;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文