How can I find the start-date and name (1, 2, 3, etc.) of a quarter from a given date?
How can I find the start-date and name (1, 2, 3, etc.) of a quarter from a given date?
I think this solution would work pretty well. It takes up more line, bus is very verbose! `
private DateTime GetFirstDayOfYearlyQuarter(DateTime value)
{
switch (value.Month)
{
case 1:
case 2:
case 3:
return new DateTime(value.Year, 1, 1);
case 4:
case 5:
case 6:
return new DateTime(value.Year, 4, 1);
case 7:
case 8:
case 9:
return new DateTime(value.Year, 7, 1);
case 10:
case 11:
case 12:
return new DateTime(value.Year, 10, 1);
default:
throw new Exception(@"¯\_(ツ)_/¯");
}
}
`
P.S. This only finds first day of quarter, but you can easily extend this to find number of quarter, etc.
DateTime date;
int quarterNumber = (date.Month-1)/3+1;
DateTime firstDayOfQuarter = new DateTime(date.Year, (quarterNumber-1)*3+1,1);
DateTime lastDayOfQuarter = firstDayOfQuarter.AddMonths(3).AddDays(-1);
A simpler two liner with live demo here + press F8 to run .
var date = DateTime.Now; //Give you own DateTime
int offset = 2, monthsInQtr = 3;
var quarter = (date.Month + offset) / monthsInQtr; //To find which quarter
var totalMonths = quarter * monthsInQtr;
var startDateInQtr = new DateTime(date.Year, totalMonths - offset, 1); //start date in quarter
If you are looking at last day of the quarter use DateTime.DaysInMonth
var endDateInQtr = new DateTime(date.Year, totalMonths, DateTime.DaysInMonth(date.Year, totalMonths));
public static class DateTimeExtensions
{
public static DateTime StartOfQuarter(this DateTime _date)
{
var quarter = decimal.ToInt16(Math.Ceiling(_date.Month / 3.0m));
return new DateTime(_date.Year, quarter, 1);
}
}
use
var quarterStart = DateTime.Today.StartOfQuarter();