in c#, i want a function to take current date and return the number of the last month of that quarter of the year (as a 2 character string)
So
- on Jan 1st it would return 03 (For March)
- on Dec 12, it would return 12 (For Dec)
- on Feb 25, it would return 03 (For march)
something like t开发者_高级运维his:
DateTime dt = new DateTime(
    DateTime.Today.Year,
    DateTime.Today.Month,
    DateTime.Today.Day);
String 2characterlastMonthinQuarter = CalcLastMonthInQuarter(dt);
public static int CalcLastMonthInQuarter(DateTime dt)
{
    return 3 * ((dt.Month - 1) / 3 + 1);
}
public static string CalcLastMonthInQuarterStr(DateTime dt)
{
    return CalcLastMonthInQuarter(dt).ToString("00");
}
Here, this test:
for(int month = 1; month <= 12; ++month)
{
    Console.WriteLine("{0}: {1}", month, CalcLastMonthInQuarterStr(new DateTime(2011, month, 1)));
}
prints:
1: 03
2: 03
3: 03
4: 06
5: 06
6: 06
7: 09
8: 09
9: 09
10: 12
11: 12
12: 12
((DateTime.Now.Month + 2) / 3 * 3)
I am assuming standard quarter-end dates. I strongly prefer not doing ugly arithmetic here. It's more readable and maintable. To wit:
public static string LastMonthOfQuarterAsString(DateTime date) {
    return String.Format("{0:00}", LastMonthOfQuarter(date));
}
private static int LastMonthOfQuarter(DateTime date) {
    int year = date.Year;
    DateTime[] endOfQuarters = new[] {
        new DateTime(year, 3, 31),
        new DateTime(year, 6, 30),
        new DateTime(year, 9, 30),
        new DateTime(year, 12, 31)
    };
    DateTime quarterEndForDate = endOfQuarters.First(d => date <= d);
    return quarterEndForDate.Month;                
}
public static String CalcLastMonthInQuarter(DateTime dt)
{
    return (Math.Ceiling(dt.Month / 3D) * 3).ToString("00");
}
 
         
                                         
                                         
                                         
                                        ![Interactive visualization of a graph in python [closed]](https://www.devze.com/res/2023/04-10/09/92d32fe8c0d22fb96bd6f6e8b7d1f457.gif) 
                                         
                                         
                                         
                                         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论