开发者

Nearest completed quarter

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

For example,

v开发者_C百科ar lastDayOfLastQuarter = SomeFunction(jan 3, 2010);

would set lastDayOfLastQuarter = Dec 31, 2009


public static DateTime NearestQuarterEnd(this DateTime date) {
    IEnumerable<DateTime> candidates = 
        QuartersInYear(date.Year).Union(QuartersInYear(date.Year - 1));
    return candidates.Where(d => d < date.Date).OrderBy(d => d).Last();
}

static IEnumerable<DateTime> QuartersInYear(int year) {
    return new List<DateTime>() {
        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.


Try this:
The AddMonths(-(d.Month-1) % 3)) moves the datevalue to the equivilent day of the first month in the quarter, and then the AddDays (-day) moves back to the last day of the preceding month.

  DateTime d = Datetime.Now;
  DateTime lastDayOfLastQuarter = d.AddMonths(-((d.Month-1)%3)).AddDays(-d.Day);


A simple function can calculate the last days of the most recently completed month:

public static DateTime LastQuarter(DateTime date)
{
    return new DateTime(date.Year, date.Month - ((date.Month - 1) % 3), 1).AddDays(-1);
}


Assuming quarters always end at 3 month intervals you could do:

Maybe not the best solution, but very easy to read and modify compared to other solutions offered.

public DateTime LastDayOfLastQuarter(DateTime date)
{
    int result = (int)(date.Month/3)

    switch (result)
    {
        // January - March
        case 0:
            return new DateTime(date.Year - 1, 12, 31);
        // April - June
        case 1:
            return new DateTime(date.Year, 3, 31);
        // July - September
        case 2:
            return new DateTime(date.Year, 6, 30);
        // October - December
        case 3:
            return new DateTime(date.Year, 9, 30);
    }
}


Here's a simple function to give you the last day of the current quarter (assuming you're using a standard calendar).

DateTime LastDayOfQuarter(DateTime today)
{
    int quarter = (today.Month-1) / 3;
    int lastMonthInQuarter = (quarter +1) * 3;
    int lastDayInMonth =  DateTime.DaysInMonth(today.Year, lastMonthInQuarter);
    return new DateTime(today.Year, lastMonthInQuarter, lastDayInMonth); 
}

Hope that helps.


Func<int, int> q = (i) => { return ((i - 1) / 3) + 1; };

Test:

Enumerable.Range(1, 12).Select(i => q(i));


You can use a simple switch statement to check which quarter the given date falls and return the last day of that quarter.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜