[C#]取得月初及月底的日期

  • 15056
  • 0
  • C#
  • 2012-10-09

[C#]取得本月的第一天及最後一天的日期方法

以下範例使用 使定日期 開始跑12個月的 月初跟月底出來

取得月初的方法是一樣的,取得月底 分別用這兩種方法

 

DateTime LastDay = new DateTime(cdate.AddMonths(1).Year, cdate.AddMonths(1).Month, 1).AddDays(-1);//下月初1號減一天=本月底

DateTime TheMonthEnd = new DateTime(startdate.Year, startdate.Month, DateTime.DaysInMonth(startdate.Year, startdate.Month));//本月初月底

解法1 參考[C#]取得本月的第一天及最後一天的日期方法

因為他沒寫註解,所以很不易讀。

解法2是我改進的方法,

DateTime.DaysInMonth 方法

是用來傳回指定之月份和年份中的天數。

所以我只要傳指定 的 年 跟 月 就能準確的取出 當月有幾天

當月有31天,月底自然就是31了。

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("解法1");
            DateTime cdate = new DateTime (2012,1,5);
            for (int i=1;i<12;i++)
            {
            DateTime FirstDay = new DateTime(cdate.Year, cdate.Month, 1);//本月初1號
            DateTime LastDay = new DateTime(cdate.AddMonths(1).Year, cdate.AddMonths(1).Month, 1).AddDays(-1);//下月初1號減一天=本月底
            Console.WriteLine(FirstDay.ToString("yyyy/MM/dd"));
            Console.WriteLine(LastDay.ToString("yyyy/MM/dd"));
            cdate = cdate.AddMonths(1);//加一個月
            }
            Console.WriteLine("解法2");
            DateTime startdate = new DateTime(2012, 1, 5);
            for (int i = 1; i < 12; i++)
            {
                //本月初
                DateTime TheMonthStart = new DateTime(startdate.Year, startdate.Month, 1);//本月初1號
                Console.WriteLine(TheMonthStart.ToString("yyyy/MM/dd"));
                //本月底
                DateTime TheMonthEnd = new DateTime(startdate.Year, startdate.Month, DateTime.DaysInMonth(startdate.Year, startdate.Month));//本月初月底
                Console.WriteLine(TheMonthEnd.ToString("yyyy/MM/dd"));
                startdate = startdate.AddMonths(1);//加一個月
            }
            Console.Read();
        }
    }
}


如有錯誤 歡迎指正