问题描述
我在数据库中的每条记录都有一个开始日期和结束日期.
Hi I have a Start Date and End Date per record in a db.
我需要查看时间段在 2 年期间内的位置,分为两个季度,然后显示每条记录所属的季度.
I need to check to see where the time period falls in a 2 year period broken into two lots of quarters then display what quarters each record falls into.
第 1 季度包括 6 月 9 日、7 月 9 日、8 月 9 日
第 2 季度包括 9 月 9 日、10 月 9 日和 11 月 9 日
第 3 季度包括 12 月 9 日、1 月 10 日、2 月 10 日
第 4 季度包括 3 月 10 日、4 月 10 日、5 月 10 日
Quaretr 5 包括 6 月 10 日、7 月 10 日...
Quarter 1 includes June 09, Jul 09, Aug 09
Quarter 2 includes Sept 09, Oct 09, Nov 09
Quarter 3 includes Dec 09, Jan 10, Feb 10
Quarter 4 includes Mar 10, Apr 10, May 10
Quaretr 5 includes Jun 10, Jul 10...
例如01/10/09 - 01/06/10 将分为第 2、3、4 和5
e.g. 01/10/09 - 01/06/10 would fall into quarters 2, 3, 4 & 5
我对 .NET 非常陌生,因此非常感谢任何示例.
I am very new to .NET so any examples would be much appreciated.
推荐答案
您可以按如下方式调用 IntervalInQuarters:
You would call IntervalInQuarters as follows:
IntervalInQuarters(new DateTime(2007, 10, 10), new DateTime(2009, 10, 11));
该函数返回季度开始日期的列表.请注意,搜索的季度范围是在函数本身中定义的.请根据您的情况进行适当的编辑.他们的关键是确保区间/四分之一交叉逻辑是正确的.
The function returns a list of quarter start dates. Note that the range of quarters searched is defined within the function itself. Please edit as appropriate for your situation. They key point is to make sure the interval/quarter intersection logic is right.
private List<DateTime> IntervalInQuarters(DateTime myStartDate, DateTime myEndDate)
{
DateTime quarterStart = new DateTime(2006, 06, 01);
DateTime nextQuarterStart = new DateTime(2006, 09, 01);
DateTime finalDate = new DateTime(2011, 01, 01);
List<DateTime> foundQuarters = new List<DateTime>();
while (quarterStart < finalDate)
{
// quarter intersects interval if:
// its start/end date is within our interval
// our start/end date is within quarter interval
DateTime quarterEnd = nextQuarterStart.AddDays(-1);
if (DateInInterval(myStartDate, quarterStart, quarterEnd) ||
DateInInterval(myEndDate, quarterStart, quarterEnd) ||
DateInInterval(quarterStart, myStartDate, myEndDate) ||
DateInInterval(quarterEnd, myStartDate, myEndDate))
{
foundQuarters.Add(quarterStart);
}
quarterStart = nextQuarterStart;
nextQuarterStart = nextQuarterStart.AddMonths(3);
}
return foundQuarters;
}
private bool DateInInterval(DateTime myDate, DateTime intStart, DateTime intEnd)
{
return ((intStart <= myDate) && (myDate <= intEnd));
}
这篇关于如何检查日期时间范围是否在另一个 3 个月的日期时间范围内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!