创建两个日期之间的月份数组
我有以下代码片段,用于获取两个日期之间的各个日期:
DateTime[] output = Enumerable.Range(0, 1 + endDate.Subtract(startDate).Days)
.Select(offset => startDate.AddDays(offset))
.ToArray();
但是,以下部分
endDate.Subtract(startDate).Days
没有 .Months 来返回日期范围内的月份。
例如,如果我提供 1/1/2010 和 6/1/2010,我期望返回 1/1/2010、2/1/2010、3/1/2010、4/1/2010、5/1/ 2010 年和 2010 年 6 月 1 日。
有什么想法吗?
I have the following snippet that I use to get the individual dates between two dates:
DateTime[] output = Enumerable.Range(0, 1 + endDate.Subtract(startDate).Days)
.Select(offset => startDate.AddDays(offset))
.ToArray();
However, the following section
endDate.Subtract(startDate).Days
does not have a .Months to return the months in the date range.
For example, if I provide 1/1/2010 and 6/1/2010 I would expect to return 1/1/2010, 2/1/2010, 3/1/2010, 4/1/2010, 5/1/2010 and 6/1/2010.
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
试试这个:
这包括开始月份和结束月份。这会查找有多少个月,然后根据
d0
的年份和月份创建一个新的DateTime
。这意味着月份就像yyyy-MM-01
。如果您希望它包含d0
的时间和日期,您可以将new DateTime(d0.Year, d0.Month, 1).AddMonths(m)
替换为>d0.AddMonths(m)
。我发现您需要一个数组,在这种情况下,您只需使用
monthsBetween(..., ...).ToArray()
或将.ToArray()
放入方法内。Try this:
This includes both the starting month and the ending month. This finds how many months there is, and then creates a new
DateTime
based ond0
´s year and month. That means the months are likeyyyy-MM-01
. If you want it to includes the time and day ofd0
you can replacenew DateTime(d0.Year, d0.Month, 1).AddMonths(m)
byd0.AddMonths(m)
.I see you need an array, in that case you just use
monthsBetween(..., ...).ToArray()
or put.ToArray()
inside the method.因为我只需要两个日期之间的年份和月份,所以我稍微修改了 Lasse Espeholt 的答案。认为:
d0 = 2012-11-03
d1 = 2013-02-05
结果将是这样的:
2012-11
2012-12
2013-01
2013-02
Since I just needed the year and month in between two dates I modified Lasse Espeholt answer a little. suppose:
d0 = 2012-11-03
d1 = 2013-02-05
The result will be something like this:
2012-11
2012-12
2013-01
2013-02
这是您要找的吗?这个要求非常模糊。
Is this what you are looking for? The requirement is very ambiguous.
您可以使用以下方法枚举月份的增量:
然后如果您想要一个数组,则对其调用
ToArray()
。拥有可能是想要的价值观是相当好的。例如,如果您从 1 月 31 日日开始,接下来的日期是 2 月 28 日日(闰年为 29日),然后是 3 月 31 日< super>st,然后是 4 月 30 日,依此类推。You could enumerate increments of months with:
and then call
ToArray()
on that if you want an array. It's reasonably good about having values that are likely to be what is wanted; e.g. if you start at Jan 31st you'll next get Feb 28th (or 29th on leap years), then Mar 31st, then Apr 30th and so on.