views:

1222

answers:

3

I know that Sql Server has some handy built-in quarterly stuff, but what about the .Net native DateTime object? What is the best way to add, subtract, and traverse quarters?

Is it a bad thing™ to use the VB-specific DateAdd() function? e.g.:

Dim nextQuarter As DateTime = DateAdd(DateInterval.Quarter, 1, DateTime.Now)

Edit: Expanding @bslorence's function:

Public Shared Function AddQuarters(ByVal originalDate As DateTime, ByVal quarters As Integer) As Datetime
    Return originalDate.AddMonths(quarters * 3)
End Function

Expanding @Matt's function:

Public Shared Function GetQuarter(ByVal fromDate As DateTime) As Integer
    Return ((fromDate.Month - 1) \ 3) + 1
End Function

Edit: here's a couple more functions that were handy:

Public Shared Function GetFirstDayOfQuarter(ByVal originalDate As DateTime) As DateTime
    Return AddQuarters(New DateTime(originalDate.Year, 1, 1), GetQuarter(originalDate) - 1)
End Function

Public Shared Function GetLastDayOfQuarter(ByVal originalDate As DateTime) As DateTime
    Return AddQuarters(New DateTime(originalDate.Year, 1, 1), GetQuarter(originalDate)).AddDays(-1)
End Function
+2  A: 

How about this:

Dim nextQuarter As DateTime = DateTime.Now.AddMonths(3);
Ben Dunlap
That is functionally equivalent to DateAdd(DateInterval.Quarter, 1, DateTime.Now), as is cleaner than using VB function.
Mark Brackett
+3  A: 

I know you can calculate the quarter of a date by:

Dim quarter As Integer = (someDate.Month - 1) \ 3 + 1

If you're using Visual Studio 2008, you could try bolting additional functionality on to the DateTime class by taking a look at Extension Methods.

Matt Blaine
I'd love to use extension methods! Unfortunately, this is for VS 2005/.Net 2.0. Thanks for the formula though, that'll come in handy.
travis
+1  A: 

One thing to remeber, not all companies end their quarters on the last day of a month.

Dan B
good point, I'll have to check and see if I have to match on the nearest business day (what a pain that would be!)
travis