我只是想为一年中的每个月创建一个这样的文本(链接)
May, 2013
April, 2013
March, 2013
February, 2013
January, 2013
December, 2012
为此我创建了这个for循环
var start = DateTime.Now;
var end = DateTime.Now.AddYears(20);
for (DateTime time = start; time <= end; time = time.AddMonths(1))
{
//month and year
}
但我不确定,因为它不起作用:(
答案 0 :(得分:0)
类似的东西:
DateTime endDate = new DateTime(2013, 12, 31);
List<string> list = new List<string>();
for (DateTime startDate = new DateTime(2013, 1, 1); startDate.Month <= endDate.Month; startDate = startDate.AddMonths(1))
{
list.Add(startDate.ToString("MMMM, yyyy"));
if (startDate.Month == endDate.Month)
break;
}
输出:
foreach(string str in list)
Console.WriteLine(str);
输出将是:
January, 2013
February, 2013
March, 2013
April, 2013
May, 2013
June, 2013
July, 2013
August, 2013
September, 2013
October, 2013
November, 2013
December, 2013
答案 1 :(得分:0)
您可以使用MMMM
来获取月份。
public IEnumerable<string> GetMonthsOfYear(DateTime startDate, TimeSpan timeSpan)
{
var end = startDate.Add(timeSpan);
for (DateTime time = startDate; time <= end; time = time.AddMonths(1))
{
yield return time.ToString("MMMM, yyyy");
}
}
用法:
var start = DateTime.Now;
var monthsOfYear = GetMonthsOfYear(start, start.AddYears(20) - start);