Nearest completed quarter

后端 未结 7 1238
野性不改
野性不改 2021-01-02 00:03

Is there a C# function which will give me the last day of the most recently finished Quarter given a date?

For example,

var lastDayOfLastQuarter = So         


        
7条回答
  •  余生分开走
    2021-01-02 00:10

    public static DateTime NearestQuarterEnd(this DateTime date) {
        IEnumerable candidates = 
            QuartersInYear(date.Year).Union(QuartersInYear(date.Year - 1));
        return candidates.Where(d => d < date.Date).OrderBy(d => d).Last();
    }
    
    static IEnumerable QuartersInYear(int year) {
        return new List() {
            new DateTime(year, 3, 31),
            new DateTime(year, 6, 30),
            new DateTime(year, 9, 30),
            new DateTime(year, 12, 31),
        };
    }
    

    Usage:

    DateTime date = new DateTime(2010, 1, 3);
    DateTime quarterEnd = date.NearestQuarterEnd();
    

    This method has the advantage in that if you have an odd definition of quarters (for example, fiscal year is different than calendar year) the method QuartersInYear is easily modified to handle this.

提交回复
热议问题