如何将两个日期转换为月份格式c#

时间:2012-10-12 21:44:23

标签: c# date

假设我们有两个日期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

任何代码或算法都将受到赞赏。

1 个答案:

答案 0 :(得分: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中提取了第一个/最后一个函数。)