0

我只想为一年中的每个月创建一个类似这样的文本(链接)

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
}

但我不确定,因为它不起作用:(

4

2 回答 2

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);
于 2013-05-02T13:01:57.597 回答
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
于 2013-05-02T12:56:32.567 回答