Find the First and Last Day of the Current Quarter

A very handy piece of code by Karl that finds the first and last day of the current quarter.

C#


DateTime datetime = DateTime.Now;


int currQuarter = (datetime.Month - 1) / 3 + 1;


DateTime dtFirstDay = new DateTime(datetime.Year, 3 * currQuarter - 2, 1);


DateTime dtLastDay = new DateTime(datetime.Year, 3 * currQuarter + 1, 1).AddDays(-1);


 


Response.Write("First Day of Quarter - " + dtFirstDay.ToShortDateString() + " : " +


    "Last Day of Quarter - " + dtLastDay.ToShortDateString());




VB.NET


Dim datetime As DateTime = DateTime.Now


Dim currQuarter As Integer = (datetime.Month - 1) / 3 + 1


Dim dtFirstDay As New DateTime(datetime.Year, 3 * currQuarter - 2, 1)


Dim dtLastDay As New DateTime(datetime.Year, 3 * currQuarter + 1, 1).AddDays(-1)


 


Response.Write("First Day of Quarter - " & dtFirstDay.ToShortDateString() & " : " _


& "Last Day of Quarter - " & dtLastDay.ToShortDateString())


4 comments:

  1. very useful for my application. How can i find last day of previous month using DateTime class?

    ReplyDelete
  2. Quarter 4 was giving me fits. I changed to...

    Dim currQuarter As Integer = CType((Date.Today.Month - 1) / 3 + 1, Integer)
    Dim dtFirstDay As Date = New DateTime(Date.Today.Year, 3 * currQuarter - 2, 1)
    Dim dtLastDay As Date = New DateTime(dtFirstDay.Year, dtFirstDay.Month + 2, 1).AddMonths(1).AddDays(-1)

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
  4. You should specify order of precedence

    (datetime.Year, 3 * currQuarter - 2, 1)

    (datetime.Year, (3 * currQuarter) - 2, 1) OR
    (datetime.Year, 3 * (currQuarter - 2), 1)

    ReplyDelete