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())







About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

4 comments:

Rogek said...

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

clanou said...

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)

labilbe said...
This comment has been removed by the author.
Tom Brune said...

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)