-3

假设我们有两个日期 2012-10-10 和 2012-12-31。我想在这样的表中输入数据

Start Date                 End Date
2012-10-10               2012-10-31
2012-11-01               2012-11-30
2012-12-01               2012-12-31

任何代码或算法将不胜感激。

4

1 回答 1

2

像这样的东西:

class Program
{
    public static DateTime FirstDayOfMonthFromDateTime(DateTime dateTime)
    {
        return new DateTime(dateTime.Year, dateTime.Month, 1);
    }

    public static DateTime LastDayOfMonthFromDateTime(DateTime dateTime)
    {
        DateTime firstDayOfTheMonth = new DateTime(dateTime.Year, dateTime.Month, 1);
        return firstDayOfTheMonth.AddMonths(1).AddDays(-1);
    }

    static void Main(string[] args)
    {
        var date1 = new DateTime(2012, 10, 10);
        var date2 = new DateTime(2012, 12, 31);
        Console.Out.WriteLine(date1.ToShortDateString() + "\t" + LastDayOfMonthFromDateTime(date1).ToShortDateString());
        while (LastDayOfMonthFromDateTime(date1) < date2)
        {
            date1 = date1.AddMonths(1);
            Console.Out.WriteLine(FirstDayOfMonthFromDateTime(date1).ToShortDateString() + "\t" + LastDayOfMonthFromDateTime(date1).ToShortDateString());
        }

        Console.ReadLine();
    }
}

这给出了以下输出:

2012/10/10      2012/10/31
2012/11/01      2012/11/30
2012/12/01      2012/12/31

(我从devprise中提取了第一个/最后一个函数。)

于 2012-10-12T22:04:54.987 回答