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




Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 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)