September 20, 2018
Hot Topics:

# Figuring Out Quarters in .NET

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

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.

Comment and Contribute

(Maximum characters: 1200). You have characters left.

## Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

By submitting your information, you agree that developer.com may send you developer offers via email, phone and text message, as well as email offers about other products and services that developer believes may be of interest to you. developer will process your information in accordance with the Quinstreet Privacy Policy.

## Most Popular Developer Stories

Thanks for your registration, follow us on our social networks to keep up-to-date