Code below gives us the start date and end dates of previous quarter of the current day. :)
private void button1_Click(object sender, EventArgs e)
{
DateTime startDate = default(DateTime);
DateTime endDate = default(DateTime);
string lastQuarter = GetLastQuarterDates(DateTime.Now.Month);
SetLastQuarterDates(out startDate, out endDate, lastQuarter);
label1.Text = Convert.ToString(startDate);
label2.Text = Convert.ToString(endDate);
}
private void SetLastQuarterDates(out DateTime startDate, out DateTime endDate, string quarter)
{
int startMonth = 0;
int startYear = DateTime.Now.Year;
int startDay = 1;
int endMonth = 0;
int endYear = DateTime.Now.Year;
int endDay = 31;
switch (quarter)
{
case "Q1":
startMonth = 1;
endMonth = 3;
endDay = 30;
break;
case "Q2":
startMonth = 4;
endMonth = 6;
break;
case "Q3":
startMonth = 7;
endMonth = 9;
endDay = 30;
break;
case "Q4":
startMonth = 10;
startYear = DateTime.Now.Year - 1;
endMonth = 12;
endYear = DateTime.Now.Year - 1;
break;
}
startDate = new DateTime(startYear, startMonth, startDay);
endDate = new DateTime(endYear, endMonth, endDay);
}
private string GetLastQuarterDates(int month)
{
string quarter = string.Empty;
if (month >= 1 && month <= 3)
{
quarter = "Q4";
}
if (month >= 4 && month <= 6)
{
quarter = "Q1";
}
if (month >= 7 && month <= 9)
{
quarter = "Q2";
}
if (month >= 10 && month <= 12)
{
quarter = "Q3";
}
return quarter;
}