April 24, 2008

Date functions: something new every day

Ok, I didn't know about DateSerial. I stumbled on it while looking for some code to manipulate dates and get stuff like first day of month and last day of month. I am adding functions to a utility class so that I can send the a date and get the date range for the previous month or previous quarter.

I Googled and found a link in the MS Asp.Net forum, this linked to a 4GuysFromRolla FAQ entry on DateFunctions

A little fiddling and twiddling resulted in this:

  Public Shared Function GetPreviousQuarterDateRange(ByVal currDate As DateTime) As DateTime()
      Dim dateRange(1) As DateTime

      dateRange(0) = CDate(DateSerial(currDate.Year, currDate.Month - 3, 1))
      dateRange(1) = CDate(DateSerial(currDate.Year, currDate.Month, 1 - 1))

      Return dateRange

  End Function

and this:

  Public Shared Function GetPreviousMonthDateRange(ByVal currDate As DateTime) As DateTime()
      Dim dateRange(1) As DateTime


      dateRange(0) = CDate(DateSerial(currDate.Year, currDate.Month - 1, 1))
      dateRange(1) = CDate(DateSerial(currDate.Year, currDate.Month, 1 - 1))

      Return dateRange
  End Function

In that forum, the response from Peter Blum advocated DateTime functions, for example, to get the last day of a month:

      new DateTime(currentyear, currentmonth, 1).AddMonth(1).AddDay(-1)

Hmmm... both approaches work... not sure which one is more 'correct'.

Posted by buggy at April 24, 2008 02:33 PM