Skip to content

Instantly share code, notes, and snippets.

@SamWM
Last active January 3, 2016 21:49
Show Gist options
  • Save SamWM/8524126 to your computer and use it in GitHub Desktop.
Save SamWM/8524126 to your computer and use it in GitHub Desktop.
Return the input DateTime values current financial month, year or both
public static int FinancialMonth(DateTime date)
{
int month = date.Month - 3;
if (date.Month <= 3)
{
month = month + 12;
}
return month;
}
public static int FinancialYear(DateTime date)
{
int year = date.Year;
if (date.Month <= 3)
{
year = year - 1;
}
return year;
}
public static string FinancialMonthYear(DateTime date, bool leadingZero = true)
{
if(leadingZero)
{
return string.Format("{0:00}/{1}", FinancialMonth(date), FinancialYear(date));
}
else
{
return string.Format("{0}/{1}", FinancialMonth(date), FinancialYear(date));
}
}
public static int FinancialQuarter(DateTime date)
{
return ((((date.Month - 1) / 3) + 3) % 4) + 1;
}
public static DateTime FirstDayInQuarter(DateTime date)
{
return FirstDayInQuarter(FinancialQuarter(date), date);
}
public static DateTime LastDayInQuarter(DateTime date)
{
return LastDayInQuarter(FinancialQuarter(date), date);
}
public static DateTime FirstDayInQuarter(int quarter, DateTime date)
{
var year = date.Year;
if (quarter == 4)
{
year = year - 1;
}
return new DateTime(year, 1, 1).AddMonths(3 * quarter);
}
public static DateTime LastDayInQuarter(int quarter, DateTime date)
{
var year = date.Year;
if (quarter == 4)
{
year = year - 1;
}
return new DateTime(year, 1, 1).AddMonths((3 * quarter) + 3).AddSeconds(-1);
}
public static DateTime DateFromQuarter(int quarter, int year, bool lastDay = false)
{
if (quarter == 4) year++;
var date = new DateTime(year, 1, 1);
return lastDay ? LastDayInQuarter(quarter, date) : FirstDayInQuarter(quarter, date);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment