c# - 计算 DayOfQuarter
问题描述
给定一个DateTime
对象,我想知道它是哪个季度的哪一天。
例如,第一季度2 Feb
的33
第 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;
}
解决方案
是的,我认为我们可以使用该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;
推荐阅读
- forms - 项目模板未在构建时更新
- mysql - 正则表达式查找字符串和下一个字符不应该是数字
- typescript - 找不到 TypeScript 模块文件
- r-markdown - 使用 stargazer 创建回归表时无法更改 NULL 长度错误
- python - 没有从 Yahoo-Finance 获取数据
- grouping - 在 graylog、prometheus、grafana 等工具中对历史警报进行分组
- java - 在没有用户和密码数据的情况下使用 java 在 WebSphere MQ 上配置 jms
- python - 如何使用额外的图像相关参数在 Keras 中创建自定义成本函数?
- r - 在R中加载xlsx包的java版本错误
- angular - 如何在单击highcharts angular中的x范围图时动态创建时间线图