我如何发现给定日期的四分之一

ven*_*kat 32 c#

以下是一个财政年度的宿舍

April to June          - Q1
July to Sep            - Q2
Oct to Dec             - Q3
Jan to March           - Q4
Run Code Online (Sandbox Code Playgroud)

如果输入日期的月份如上所述,我需要以季度数表示的输出.

例如,

如果我给出输入日期(比如1月2日),我需要输出为Q4.

如果我输入为(6月5日),输出应该给出Q1.

根据输入日期,我需要季度编号.

wez*_*zix 49

如果您更喜欢没有分支和数组的简短解决方案,这是我的首选解决方案.

正常季度:

public static int GetQuarter(this DateTime date)
{
    return (date.Month + 2)/3;
}
Run Code Online (Sandbox Code Playgroud)

财政年度季度:

public static int GetFinancialQuarter(this DateTime date)
{
    return (date.AddMonths(-3).Month + 2)/3;
}
Run Code Online (Sandbox Code Playgroud)

整数除法将截断小数,为您提供整数结果.将方法放入静态类,您将有一个扩展方法,如下所示:

date.GetQuarter()
date.GetFinancialQuarter()
Run Code Online (Sandbox Code Playgroud)

dotnetfiddle


Har*_*san 24

您只需向DateTime编写扩展方法即可

public static int GetQuarter(this DateTime date)
{
    if (date.Month >= 4 && date.Month <= 6)
        return 1;
    else if (date.Month >= 7 && date.Month <= 9)
        return 2;
    else if (date.Month >= 10 && date.Month <= 12)
        return 3;
    else 
        return 4;
}
Run Code Online (Sandbox Code Playgroud)

并用它作为

DateTime dt = DateTime.Now;
dt.GetQuarter();
Run Code Online (Sandbox Code Playgroud)


Dom*_*nik 16

这是"正常年份".我想你可以调整样本:

string.Format("Q{0}", (date.Month + 2)/3);
Run Code Online (Sandbox Code Playgroud)


Max*_*tiy 12

public static int GetQuarter(DateTime date)
{
    int[] quarters = new int[] { 4,4,4,1,1,1,2,2,2,3,3,3 };
    return quarters[date.Month-1];
}
Run Code Online (Sandbox Code Playgroud)


小智 10

实现这一目标的最简单一致的方法:


定期

Math.Ceiling(date.Month / 3.0)
Run Code Online (Sandbox Code Playgroud)

财政(刚刚上调了2 + 1个季度)

Math.Ceiling(date.Month / 3.0 + 2) % 4 + 1
Run Code Online (Sandbox Code Playgroud)
01.01.2016 00:00:00 -> Q1 -> FQ4
01.02.2016 00:00:00 -> Q1 -> FQ4
01.03.2016 00:00:00 -> Q1 -> FQ4
01.04.2016 00:00:00 -> Q2 -> FQ1
01.05.2016 00:00:00 -> Q2 -> FQ1
01.06.2016 00:00:00 -> Q2 -> FQ1
01.07.2016 00:00:00 -> Q3 -> FQ2
01.08.2016 00:00:00 -> Q3 -> FQ2
01.09.2016 00:00:00 -> Q3 -> FQ2
01.10.2016 00:00:00 -> Q4 -> FQ3
01.11.2016 00:00:00 -> Q4 -> FQ3
01.12.2016 00:00:00 -> Q4 -> FQ3
Run Code Online (Sandbox Code Playgroud)

结果是介于1和4之间的值.几乎任何环境都具有CEIL功能,因此这也适用于任何语言.


小智 6

int CurrentQuarter = (int)Math.Floor(((decimal)DateTime.Today.Month + 2) / 3);
Run Code Online (Sandbox Code Playgroud)

或将DateTime.Today更改为所需日期.


Den*_*Den 6

扩展方法和较少的比较:

public static class DateTimeExtension
{
    public static int GetQuarter(this DateTime dateTime)
    {
        if (dateTime.Month <= 3)
            return 1;

        if (dateTime.Month <= 6)
            return 2;

        if (dateTime.Month <= 9)
            return 3;

        return 4;
    }
}
Run Code Online (Sandbox Code Playgroud)