最近完成的季度

时间:2009-12-22 15:44:43

标签: c# .net date

是否有一个C#函数会给我一个最近完成的季度的最后一天给出一个日期?

例如,

var lastDayOfLastQuarter = SomeFunction(jan 3, 2010);

将设置lastDayOfLastQuarter = 2009年12月31日

7 个答案:

答案 0 :(得分:26)

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),
    };
}

用法:

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

此方法的优势在于,如果您有一个奇数的季度定义(例如,会计年度与日历年不同),则可以轻松修改方法QuartersInYear以处理此问题。

答案 1 :(得分:2)

试试这个:
  AddMonths(-(d.Month-1) % 3))将日期值移至季度中第一个月的等效日,然后AddDays (-day)移回上个月的最后一天。

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

答案 2 :(得分:2)

假设季度总是以3个月的间隔结束,您可以这样做:

与其他提供的解决方案相比,可能不是最佳解决方案,但非常容易阅读和修改。

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);
    }
}

答案 3 :(得分:2)

一个简单的函数可以计算最近完成的月份的最后几天:

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

答案 4 :(得分:1)

这是一个简单的功能,可以为您提供当前季度的最后一天(假设您使用的是标准日历)。

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); 
}

希望有所帮助。

答案 5 :(得分:1)

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

测试:

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

答案 6 :(得分:0)

您可以使用简单的switch语句来检查给定日期的哪个季度,并返回该季度的最后一天。

相关问题