[.NET] 当月の末日を取得

日付関連を扱うと割と使う末日取得

.NET(C#やVB.NET)ではDATE型とDATETIME型にDaysInMonthというメソッドで指定した年、月の日数を取得する。
http://msdn.microsoft.com/ja-jp/library/system.datetime.daysinmonth%28v=vs.110%29.aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1

 

DaysInMonthを使って、当月(例では本日)、当月の1日、当月の末日を取得したい場合は下記のようになる。

C#

var today = DateTime.Now;
var firstDayInMonth = new DateTime(today.Year, today.Month, 1);
var lastDayInMonth = new DateTime(today.Year, today.Month, DateTime.DaysInMonth(today.Year, today.Month));

VB.NET

Dim today As Date = Date.Now()
Dim firstDayInMonth As Date = New Date(today.Year, today.Month, 1)
Dim lastDayInMonth As Date = New Date(today.Year, today.Month, Date.DaysInMonth(today.Year, today.Month))

しかし、オブジェクト指向なんだから、上の図でいうなら、today.DaysInMonth() といった感じで、静的メソッドだけじゃなくて、インスタンスのメソッドとして使えたらよりすっきりする気がするのは自分だけだろうか。

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>