Expanding Upon Getting the Days in a Month

I was perusing the ASP.NET forums tonight and saw an entry where the person was asking on help on getting the number of days in a month in .NET. While the asker was making a simple mistake and could not see the forest for the trees, it got me thinking about why there was no overloads to simply return the number of days by passing in a date.

The DateTime class has a Shared method, DaysInMonth, that returns the number of days in the month. It does require the numerical value of the year and the month. While this can be used for just about any instance, it does seem a bit cumbersome in common cases where you have a DateTime value.

The following example will not work.

DateTime.DaysInMonth(Now())

I preach to my students about the importance of refactoring code into manageable units and to make things as easy to do now and in the future. So I took a few minutes to create a few overloaded methods to accept a DateTime or a SmartDate object and return the number of days. I then extended it to allow a string to be passed into corresponding overloaded methods to return a formatted message with the number of days nicely packed in.

Public Class ExUtility#Region " DaysInMonth " Public Shared Function DaysInMonth(ByVal vDate As DateTime) As Integer  Return DateTime.DaysInMonth(vDate.Year, vDate.Month) End Function Public Shared Function DaysInMonth(ByVal vDate As SmartDate) As Integer  Return DaysInMonth(vDate.Date) End Function Public Shared Function DaysInMonth(ByVal vDate As DateTime, ByVal vMessageFormat As String) As String  Return String.Format(vMessageFormat, DaysInMonth(vDate)) End Function Public Shared Function DaysInMonth(ByVal vDate As SmartDate, ByVal vMessageFormat As String) As Integer  Return DaysInMonth(vDate.Date, vMessageFormat) End Function#End RegionEnd Class

Now you can simply call any of these Shared methods to either get the number of days in the month or a predefined message with the value. This should cover many instances you could call, without having to write more code to get the year and month values.

Share This Article With Your Friends!