季度结束日期

时间:2017-12-18 15:56:14

标签: c# datetime modulo

对于我来说,最简单的方法是根据月份来分配季度结束月份?

我可以像模数一样使用吗?我想要最简单的案例和最少量的代码行

我的季度结束月份是3,6,9和12个月。

我想避免做这样的逻辑:

if (1 <= mymonth && mymonth <= 3)
    mymonth = new DateTime(DateTime.Now.Year, 3, 15);
else if (4 <= mymonth && mymonth <= 6)
    mymonth = new DateTime(DateTime.Now.Year, 6, 15);
else if (7 <= mymonth && mymonth <= 9)
    mymonth = new DateTime(DateTime.Now.Year, 9, 15);
else
    mymonth = new DateTime(DateTime.Now.Year, 12, 15);

3 个答案:

答案 0 :(得分:1)

您可以使用:

var quarterEndMonth = 3 * Math.Ceiling((double)currentMonth / 3);

Demonstration

答案 1 :(得分:0)

这个怎么样?

public DateTime GetQuarterEnd(int month)
{
    if (month < 1 || month > 12)
        throw new ArgumentException("month is not a valid Month of the year.");

    var mod = month % 3;
    var actual = month / 3 + (mod > 0 ? 1 : 0);
    return new DateTime(DateTime.Now.Year, actual * 3, 15);
}

答案 2 :(得分:0)

最少量的行可能是这样的:

var d = new DateTime(DateTime.Now.Year, 3*(1+(mymonth-1)/3), 15);

但这很丑陋地说:)

https://dotnetfiddle.net/HZfFLF