首页 > 解决方案 > 计算 DayOfQuarter

问题描述

给定一个DateTime对象,我想知道它是哪个季度的哪一天。

例如,第一季度2 Feb33第 3 天。

我可以像这样从一个月中获得季度: (int)System.Math.Ceiling(month / (double)3)

我还可以用它DateTime.DaysInMonth()来找出每个季度有多少天。

我写了这个特别难看的方法,希望有人能指出我(很明显)我确定我错过了。

public static int DayOfQuarter(DateTime dt)
        {
            var quarter = GetQuarter(dt);

            int[] months = new int[0];
            switch (quarter)
            {
                case 1:
                    months = new[] { 1, 2, 3 };
                    break;
                case 2:
                    months = new[] { 4, 5, 6 };
                    break;
                case 3:
                    months = new[] { 7, 8, 9 };
                    break;
                case 4:
                    months = new[] { 10, 11, 12 };
                    break;
            }

            var idx = -1;
            for (var i = 0; i < months.Length; i++)
            {
                if (months[i] == dt.Month)
                {
                    idx = i;
                }
            }

            if (idx == 0)
            {
                return dt.Day;
            }

            if (idx == 1)
            {
                return DateTime.DaysInMonth(dt.Year, dt.Month - 1) + dt.Day;
            }

            return DateTime.DaysInMonth(dt.Year, dt.Month - 2) + DateTime.DaysInMonth(dt.Year, dt.Month - 1) + dt.Day;
        }

标签: c#

解决方案


是的,我认为我们可以使用该DayOfYear属性使这更简单。您只需要能够计算出季度的开始,然后您就可以从指定日期的年份中获取该日期的年份。

public static int DayOfQuarter(DateTime dt)
{
    int zeroBasedQuarter = (dt.Month - 1) / 3;
    DateTime startOfQuarter = new DateTime(dt.Year, zeroBasedQuarter * 3 + 1, 1);
    return dt.DayOfYear - startOfQuarter.DayOfYear + 1;
}

这是一个简短但完整的测试应用程序:

using System;

public class Program
{
    static void Main()
    {
        var dates = new[]
        {
            new DateTime(2000, 1, 1),
            new DateTime(2001, 1, 1),
            new DateTime(2000, 3, 1),
            new DateTime(2001, 3, 1),
            new DateTime(2000, 4, 1),
            new DateTime(2001, 4, 1),
            new DateTime(2000, 5, 1),
            new DateTime(2001, 5, 1),
            new DateTime(2000, 12, 31),
            new DateTime(2001, 12, 31),
        };
        foreach (var date in dates)
        {
            int dayOfQuarter = DayOfQuarter(date);
            Console.WriteLine($"{date:yyyy-MM-dd}: {dayOfQuarter}");
        }
    }

    public static int DayOfQuarter(DateTime dt)
    {
        int zeroBasedQuarter = (dt.Month - 1) / 3;
        DateTime startOfQuarter = new DateTime(dt.Year, zeroBasedQuarter * 3 + 1, 1);
        return dt.DayOfYear - startOfQuarter.DayOfYear + 1;
    }
}

输出:

2000-01-01: 1
2001-01-01: 1
2000-03-01: 61
2001-03-01: 60
2000-04-01: 1
2001-04-01: 1
2000-05-01: 31
2001-05-01: 31
2000-12-31: 92
2001-12-31: 92

请注意第三行和第四行,表明它在闰年做正确的事情(其中 3 月 1 日的季度日比闰年大一个)。

我还建议避免为您的方法使用浮点GetQuarter- 这是不必要的:

public static int GetQuarter(DateTime dt) => (dt.Month - 1) / 3 + 1;

推荐阅读