我需要的是弄清楚如何在两个日期之间获取monthname-year的逻辑。
Dictionary<Monthname,year> GetMonthsandYear(Datetime d1,Datetime d2)
or
List<Tuple<string,int> GetMonthsandYear(Datetime d1,Datetime d2)
范例:2013年1月1日至2013年3月3日
应以list.reverse返回2013年1月,2013年2月,2013年3月或以相反的格式
如果您的实际需求是“过去24个月”,那么它要简单得多。只需从当前月份开始,并获得它的第一天-然后进行迭代并添加1个月24次。
我个人将返回一个IEnumerable<DateTime>
而不是其他任何内容-您可以根据需要设置每个元素的格式-但这很简单:
public static IEnumerable<DateTime> GetMonths(int count)
{
// Note: this uses the system local time zone. Are you sure that's what
// you want?
var today = DateTime.Today;
// Always return the 1st of the month, so we don't need to worry about
// what "March 30th - 1 month" means
var startOfMonth = new DateTime(today.Year, today.Month, 1);
for (int i = 0; i < count; i++)
{
yield return startOfMonth;
startOfMonth = startOfMonth.AddMonths(-1);
}
}
然后,如果您想将List<string>
这些值中的a作为“ 2014年2月”等,则可以:
var monthYears = GetMonths(24).Select(dt => dt.ToString("MMMM yyyy"))
.ToList();
需要注意的是一个Dictionary<...>
会不会,除非你真的不在乎的顺序是适当的-我怀疑你做的。Dictionary<TKey, TValue>
当您将序列视为序列时,您不应该依赖于项从中返回的顺序-它不是要作为有序集合。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句