Figuring Out Quarters in .NET

CodeGuru content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

Business applications often need to figure out quarters—the four three-month periods in any year—beginning at the start of January and going through to the end of March, then April to June, July to September, and finally, October to December.

Calculating the opening and closing quarter dates for a particular date is a common task for programmers. So, to save you from figuring out how to write that code, the following ready-to-run functions do it all for you:

Public Function FirstDayOfQuarter(ByVal DateIn As DateTime) _
       As DateTime
   ' Calculate first day of DateIn quarter,
   ' with quarters starting at the beginning of Jan/Apr/Jul/Oct
   Dim intQuarterNum As Integer = (Month(DateIn) - 1)  3 + 1
   Return DateSerial(Year(DateIn), 3 * intQuarterNum - 2, 1)
End Function


Public Function LastDayOfQuarter(ByVal DateIn As Date) As Date
   ' Calculate last day of DateIn quarter,
   ' with quarters ending at the end of Mar/Jun/Sep/Dec
   Dim intQuarterNum As Integer = (Month(DateIn) - 1)  3 + 1
   Return DateSerial(Year(DateIn), 3 * intQuarterNum + 1, 0)
End Function

To use either of these functions, simply pass in the date for which you wish to retrieve the quarter, and it’ll return the appropriate beginning/end date as a DateTime data type (an exact equivalent of the Date data type).

And here’s an example of how you might call these functions:

Dim CurrentQuarterStart As Date = FirstDayOfQuarter(Now)
Dim CurrentQuarterEnd As Date = LastDayOfQuarter(Now)
MessageBox.Show("Current quarter start: " & CurrentQuarterStart & _
   Chr(10) & Chr(13) & "Current quarter end: " & CurrentQuarterEnd)

About the Author

Karl Moore (MCSD, MVP) is an experience author living in Yorkshire, England. He is author of numerous technology books, including the new Ultimate VB .NET and ASP.NET Code Book (ISBN 1-59059-106-2, $49.99), plus regularly features at industry conferences and on BBC radio. Moore also runs his own creative consultancy, White Cliff Computing Ltd. Visit his official Web site at www.karlmoore.com.

More by Author

Previous article
Next article

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read