生成每周日期

ove*_*ove 2 c# silverlight wpf date winforms

我确信这已经完成,所以我正在寻找一个有效的解决方案,而不是自己的自定义解决方案.

鉴于2个日期,我正在尝试生成准确的每周日期(用于创建每周订单).

编辑:我需要使用.NET标准库来执行此操作.

Example below,

Given 28/02/2012 and 6/03/2012.

so, the weekly dates generated are
- Week From(Start Monday):   Week To(End Sunday):
- 27/02/2012               - 04/03/2012
- 05/03/2012               - 11/03/2012

Another example (1 month)

Given 01/02/2012 and 29/02/2012
so, the weekly dates generated are
- Week From(Start Monday):   Week To(End Sunday):
- 30/01/2012               - 05/02/2012
- 06/02/2012               - 12/02/2012
- 13/02/2012               - 19/02/2012
- 20/02/2012               - 26/02/2012
- 27/02/2012               - 04/03/2012
Run Code Online (Sandbox Code Playgroud)

我在c#中这样做.以前做过吗?介意分享解决方案?

干杯

Jon*_*eet 7

这是使用Noda Time的解决方案.不可否认,它需要一个<=我现在正在实施的操作员 - 但这不应该花费很长时间:)

using System;
using NodaTime;

class Test
{
    static void Main()
    {
        ShowDates(new LocalDate(2012, 2, 28), new LocalDate(2012, 3, 6));
        ShowDates(new LocalDate(2012, 2, 1), new LocalDate(2012, 2, 29));
    }

    static void ShowDates(LocalDate start, LocalDate end)
    {
        // Previous is always strict - increment start so that
        // it *can* be the first day, then find the previous
        // Monday
        var current = start.PlusDays(1).Previous(IsoDayOfWeek.Monday);
        while (current <= end)
        {
            Console.WriteLine("{0} - {1}", current,
                              current.Next(IsoDayOfWeek.Sunday));
            current = current.PlusWeeks(1);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

显然,也可以在正常情况下执行此操作DateTime,但是没有真正表示"只是一个日期"会使代码变得不那么清晰 - 而且您需要Previous自己实现.

编辑:例如,在这种情况下,您可以使用:

using System;

class Test
{
    static void Main()
    {
        ShowDates(new DateTime(2012, 2, 28), new DateTime(2012, 3, 6));
        ShowDates(new DateTime(2012, 2, 1), new DateTime(2012, 2, 29));
    }

    static void ShowDates(DateTime start, DateTime end)
    {
        // In DateTime, 0=Sunday
        var daysToSubtract = ((int) start.DayOfWeek + 6) % 7;
        var current = start.AddDays(-daysToSubtract);        

        while (current <= end)
        {
            Console.WriteLine("{0} - {1}", current, current.AddDays(6));
            current = current.AddDays(7);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)