列出个月两个日期之间 [英] List the months between two dates
本文介绍了列出个月两个日期之间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道给定的起始和终止日期时,怎么能在两个日期之间的月和年(S)进行检索。
I would like to know when given start and end dates, how can the months and year(s) between the two dates be retrieved.
例如:开始日期:1/1/2011(MM / DD / YYYY)
和结束日期:'11 / 30 / 2011
。
几个月甚至一年要检索的 2011年1月; 2011年2月; 2011年3月;等等,直到2011年11月
推荐答案
下面我们去
public static IEnumerable<Tuple<string, int>> MonthsBetween(
DateTime startDate,
DateTime endDate)
{
DateTime iterator;
DateTime limit;
if (endDate > startDate)
{
iterator = new DateTime(startDate.Year, startDate.Month, 1);
limit = endDate;
}
else
{
iterator = new DateTime(endDate.Year, endDate.Month, 1);
limit = startDate;
}
var dateTimeFormat = CultureInfo.CurrentCulture.DateTimeFormat;
while (iterator <= limit)
{
yield return Tuple.Create(
dateTimeFormat.GetMonthName(iterator.Month),
iterator.Year);
iterator = iterator.AddMonths(1);
}
}
和显然你这样称呼它
var startDate = DateTime.ParseExact("01/01/2011", "MM/dd/yyyy");
var endDate = DateTime.ParseExact("11/30/2011", "MM/dd/yyyy");
var months = MonthsBetween(startDate, endDate);
结果应该是这样的。
The results should be something like
{
{ "January", 2011 },
{ "February", 2011 },
{ "March", 2011 },
{ "April", 2011 },
{ "May", 2011 },
{ "June", 2011 },
{ "July", 2011 },
{ "August", 2011 },
{ "September", 2011 },
{ "October", 2011 },
{ "November", 2011 },
}
月份名称依赖于你的文化,我认为这,正是你问什么,对吧?
The month names being dependent on your culture which, I think, is exactly what you asked for, right?
这篇关于列出个月两个日期之间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文