C# 从给定日期循环数月和数年的简单方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19827148/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 15:56:47  来源:igfitidea点击:

easy way to loop over months and years from a given date

c#date

提问by Rochelle C

I have been trying to write this loop and it just keeps getting more complicated. Basically I want to take a given date and loop through every month until I reach the current month. So if the start date is 11/1/2011 then I want to loop through

我一直在尝试编写这个循环,但它变得越来越复杂。基本上我想取一个给定的日期并每个月循环,直到我到达当月。所以如果开始日期是 11/1/2011 那么我想循环

11/2011, 12/2011, 1/2012, 2/2012, etc.

11/2011、12/2011、1/2012、2/2012 等

Here is what I started with but this does not work. Once I hit a new year I need the inner loop to start over with 1 not startdate.Month. Is there a better way in general to loop through months and years? Thanks

这是我的开始,但这不起作用。一旦我进入新的一年,我需要内部循环从 1 开始,而不是 startdate.Month。一般有没有更好的方法来循环几个月和几年?谢谢

        for (var y = startdate.Year; y <= DateTime.Now.Year; y++)
        {
            for (var m = startdate.Month; m <= 12; m++)
            {
                  //do something with m and y
            }
        }

采纳答案by Sam Axe

Date target = new Date(2011, 4, 1);
while (target < Date.Today) {
  // do something with target.Month and target.Year
  target = target.AddMonths(1);
}

回答by Sudhakar Tillapudi

while (startDate <= DateTime.Now)
            {
                //here you will get every new month in  year
                Console.WriteLine(startDate.Month);
                //Add Month
                startDate=startDate.AddMonths(1);
            }

回答by Matt Johnson-Pint

DateTime endDate = DateTime.Today;
for (DateTime dt = startDate; dt <= endDate; dt = dt.AddMonths(1))
{
    Console.WriteLine("{0:M/yyyy}", dt);
}

But if you prefer while loops, then vote for Dan-o. I did. :)

但是,如果您更喜欢 while 循环,那么请投票给 Dan-o。我做到了。:)

回答by esteewhy

Generate a range (as IEnumerable`DateTime) of first days of a month in between of a given dates:

生成给定日期之间一个月第一天的范围(如 IEnumerable`DateTime):

from range in new[] {
    new {
        start = new DateTime(2017, 6, 23),
        end = new DateTime(2018, 09, 11)
    }
}
select (
    from y in Enumerable.Range(
        range.start.Year, range.end.Year - 
        range.start.Year + 1
    )
    let ms = y == range.start.Year ? range.start.Month : 1
    let me = y == range.end.Year ? range.end.Month : 12
    select 
        from m in Enumerable.Range(ms, me - ms + 1)
        select new DateTime(y, m, 1)
).SelectMany(y => y)

回答by Hüseyin Ya?l?

This will loop over the months and the day of the month will not be a problem.

这将在几个月内循环,一个月中的哪一天不会有问题。

var date = startDate;
var endDate = DateTime.Now;

while(date.Year < endDate.Year || (date.Year == endDate.Year && date.Month <= endDate.Month))
{
    Console.WriteLine($"{date.Month}/{date.Year}");
    date = date.AddMonths(1);
}

回答by Slothario

Sam's answer is nice but ultimately incorrect (if your start day is 20 and your end day is 10, it won't include the last month). Here's a version that works:

Sam 的回答很好,但最终是不正确的(如果您的开始日是 20,结束日是 10,则不包括上个月)。这是一个有效的版本:

    public void GetMonths(DateTime startTime, DateTime endTime)
    {
        var dateCounter = new DateTime(startTime.Year, startTime.Month, 1);
        var endDateTarget = new DateTime(endTime.Year, endTime.Month, 1);

        while (dateCounter <= endDateTarget)
        {
            Console.WriteLine($"The year and month is: {dateCounter.Year}, {dateCounter.Month}");
            dateCounter = dateCounter.AddMonths(1);
        }
    }