[C#]取得月底的日期

  • 18102
  • 0
  • 2010-08-02

取得月底日期的兩種方式

有網友發問如何取得月底日期,一開始在網路上找,

是透過 本月月底 = 本月月初 + 1個月 - 1天 的概念計算出來

但其實可以換個方式思考,月底日期 = 當月份的天數,因此可以透過 DateTime.DaysInMonth 方法來達成
http://msdn.microsoft.com/zh-tw/library/system.datetime.daysinmonth(VS.80).aspx

程式碼

01 using System;
02 using System.Collections.Generic;
03 using System.ComponentModel;
04 using System.Data;
05 using System.Drawing;
06 using System.Text;
07 using System.Windows.Forms;

08
09 namespace DataTimeTest
10 {
11     public partial class Form1 : Form
12     {
13         public Form1()
14         {
15             InitializeComponent();
16         }

17
18         private void Form1_Load(object sender, EventArgs e)
19         {
20             this.Text = "今天的日期" + System.DateTime.Now.ToString("d");
21         }

22
23         private void button1_Click(object sender, EventArgs e)
24         {
25             // 本月月底 = 本月月初 + 1個月 - 1天
26             System.DateTime dt = System.DateTime.Now;
27             System.DateTime ThisMonBeginDay = new System.DateTime(dt.Year, dt.Month, 1);
28             System.DateTime ThisMonEndDay = ThisMonBeginDay.AddMonths(1).AddDays(-1);
29             MessageBox.Show("本月月底日期 : " + ThisMonEndDay.Day.ToString());
30         }

31
32         private void button3_Click(object sender, EventArgs e)
33         {
34             // 月底日期 = 月份的天數
35             // 透過DaysInMonth,求出指定 year 的 month 中的天數
36             MessageBox.Show("本月月底日期 : " + DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month).ToString());            
37         }

38
39         private void button2_Click(object sender, EventArgs e)
40         {
41             // 透過DaysInMonth,求出指定 year 的 month 中的天數
42             MessageBox.Show(txtYear.Text + "年" + txtMonth.Text + "月的月底日期 : " + DateTime.DaysInMonth(Convert.ToInt16(txtYear.Text), Convert.ToInt16(txtMonth.Text)).ToString());
43         }

44
45     }

46 }

執行結果

參考
http://bamboobig.blogspot.com/2008/06/c-datetime.html
http://www.cnblogs.com/babyblue/archive/2006/04/16/376276.html
http://www.blueshop.com.tw/board/show.asp?subcde=BRD20090405235751W1A&fumcde=