什么是上个月当前每季度计算的最简单方法

leo*_*ora 1 c#

在c#中,我想要一个函数来获取当前日期并返回一年中该季度的最后一个月的数字(作为2个字符的字符串)

所以

  • 在1月1日它将返回03(3月)
  • 在12月12日,它将返回12(12月)
  • 在2月25日,它将返回03(3月)

这样的事情:

DateTime dt = new DateTime(
    DateTime.Today.Year,
    DateTime.Today.Month,
    DateTime.Today.Day);

String 2characterlastMonthinQuarter = CalcLastMonthInQuarter(dt);
Run Code Online (Sandbox Code Playgroud)

Mor*_*gil 7

public static int CalcLastMonthInQuarter(DateTime dt)
{
    return 3 * ((dt.Month - 1) / 3 + 1);
}

public static string CalcLastMonthInQuarterStr(DateTime dt)
{
    return CalcLastMonthInQuarter(dt).ToString("00");
}
Run Code Online (Sandbox Code Playgroud)

在这里,这个测试:

for(int month = 1; month <= 12; ++month)
{
    Console.WriteLine("{0}: {1}", month, CalcLastMonthInQuarterStr(new DateTime(2011, month, 1)));
}
Run Code Online (Sandbox Code Playgroud)

打印:

1: 03
2: 03
3: 03
4: 06
5: 06
6: 06
7: 09
8: 09
9: 09
10: 12
11: 12
12: 12
Run Code Online (Sandbox Code Playgroud)