# Datetime extension

• ### Question

• Hello,

I'm trying to write a DateTime extension as per following. I was able to write logic for ThisMonth/LastMonth and ThisYear/LastYear.

How do I go about writing logic for ThisQuarter and LastQuarter please?

Thanks.

public static class MyDateTimeExtension

{

public static DateTime GetFirstDayofThisQuarter(this Datetime)

{

}

public static DateTime GetLastDayofThisQuarter(this Datetime)

{

}

public static DateTime GetFirstDayofPreviousQuarter(this Datetime)

{

}

public static DateTime GetLastDayofPreviousQuarter(this Datetime)

{

}

}

Tuesday, August 21, 2018 12:50 AM

### All replies

• A quarter is a fourth of a year so that is 3 months. While you could do it mathematically I think it is just as easy to just use some simple logic.

The quarters are going to be the month ranges of 1-3, 4-6, 7-9, 10-12. So you could divide the current (month / 3) + 1 to get the quarter. Example: Oct is the 10th month, (10 / 3) + 1 = 4th quarter. Given a quarter, the first month is (quarter * 3 - 2). So the first month of the 4th quarter is (4 * 3) - 2 = 10. The first day of a month is always 1.

To get the previous quarter take the current date and subtract 3 months. Note that it could move the date to last year. Everything else remains the same.

Michael Taylor http://www.michaeltaylorp3.net

Tuesday, August 21, 2018 5:01 AM
• Hi ANi2000,

Thank you for posting here.

According to your description, here is a simple example for your reference.

``` DateTime date = DateTime.Now;
int quarterNumber = (date.Month - 1) / 3 + 1;
DateTime firstDayOfQuarter = new DateTime(date.Year, (quarterNumber - 1) * 3 + 1, 1);
DateTime FirstDayofPreviousQuarter = new DateTime(date.Year, (quarterNumber - 2) * 3 + 1, 1);

Best Regards,

Wendy

MSDN Community Support
Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

Tuesday, August 21, 2018 7:37 AM
• Or, I'll just use a switch statement on this.Month, then construct a new DateTime accordingly.

Adjust the ~LastDayof~() to get the first day of next quarter of result then do .AddDays(-1) before returning.

The performance should be similar but it's easier to get right (or ask others to check) this way.

Tuesday, August 21, 2018 7:53 AM