asp.netasp.net-2.0asp.net-3.5

Calculate StartDate and EndDate for This Quarter and Last Quarter


I need to calculate a StartDate and EndDate of a current Quarter and the previous Quarter in vb.net.


Solution

  • Forgive my lack of a VB.net-specific answer, but given a generic sort of date object with various functions in some pseudo-language (with zero-based day and month indexes)...

    //round the current month number down to a multiple of 3
    ThisQuarterStart = DateFromYearMonthDay(Today.Year,Today.Month-(Today.Month%3),0);
    //round the current month number up to a multiple of 3, then subtract 1 day
    ThisQuarterEnd = DateFromYearMonthDay((Today.Month<9)?(Today.Year):(Today.Year+1),(Today.Month-(Today.Month%3)+3)%12,0) - 1;
    //same as above, but minus 3 months
    LastQuarterStart = DateFromYearMonthDay((Today.Month<3)?(Today.Year-1):(Today.Year),(Today.Month-(Today.Month%3)+9)%12,0)
    LastQuarterEnd = ThisQuarterStart - 1;
    

    Edit converted above pseudocode to working VB.Net: /Stefan

    Dim ThisQuarterStart As Date = New Date(Today.Year, Today.Month - (Today.Month Mod 3) + 1, 1)  
    Dim ThisQuarterEnd As Date = New Date(CInt(IIf(Today.Month < 9, Today.Year, Today.Year + 1)), (Today.Month - (Today.Month Mod 3) + 3 Mod 12) + 1, 1).AddDays(-1)
    Dim LastQuarterStart As Date = New Date(CInt(IIf(Today.Month < 3, Today.Year - 1, Today.Year)), (Today.Month - (Today.Month Mod 3) + 9 Mod 12) + 1, 1)
    Dim LastQuarterEnd As Date = ThisQuarterStart.AddDays(-1)