如何通过Datetime在for循环中创建链接

本文关键字:创建 链接 循环 for 何通过 Datetime | 更新日期: 2023-09-27 18:11:44

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

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
}

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

如何通过Datetime在for循环中创建链接

类似于

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

您可以使用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);