Question

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
Was it helpful?

Solution

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.

OTHER TIPS

How about this:

Dim nextQuarter As DateTime = DateTime.Now.AddMonths(3);

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

Public Function GetLastQuarterStart() As Date

    GetLastQuarterStart = DateAdd(DateInterval.Quarter, -1, DateTime.Now).ToString("MM/01/yyyy")

End Function

Public Function GetLastQuarterEnd() As Date

    Dim LastQuarterStart As Date = DateAdd(DateInterval.Quarter, -1, DateTime.Now).ToString("MM/01/yyyy")
    Dim MM As String = LastQuarterStart.Month
    Dim DD As Integer = 0
    Dim YYYY As String = LastQuarterStart.Year
    Select Case MM
        Case "01", "03", "05", "07", "08", "10", "12"
            DD = 31
        Case "02"
            Select Case YYYY
                Case "2012", "2016", "2020", "2024", "2028", "2032"
                    DD = 29
                Case Else
                    DD = 28
            End Select
        Case Else
            DD = 30
    End Select

    Dim LastQuarterEnd As Date = DateAdd(DateInterval.Month, 2, LastQuarterStart)

    MM = LastQuarterEnd.Month
    YYYY = LastQuarterEnd.Year

    Return String.Format("{0}/{1}/{2}", MM, DD, YYYY)

End Function

Expanding on Matt Blaine's Answer:

Dim intQuarter As Integer = Math.Ceiling(MyDate.Month / 3)

Not sure if this would add speed benefits or not but it looks cleaner IMO

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top