如何确定日期范围内是否有生日或周年纪念
鉴于我有生日/周年日期时间,我如何确定该日期是否在特定日期范围内发生? 例如,
生日= 1/2/2000
日期范围= 12/25/2008 - 1/3/2009
我需要一种方法来确定此人的生日是否发生在该日期范围内 - 最好是用C#。
我首先将生日DateTime的年份更改为与日期范围相匹配,然后检查“新”生日DateTime是否在日期范围的开始日期和结束日期之间......但是如果日期范围跨越不同年份,就像我上面的例子 - 我不得不添加一个讨厌的if语句。 有没有更好的办法?
好的,这是我的要求
public static bool IsBirthDayInRange(DateTime birthday, DateTime start, DateTime end)
{
DateTime temp = birthday.AddYears(start.Year - birthday.Year);
if (temp < start)
temp = temp.AddYears(1);
return birthday <= end && temp >= start && temp <= end;
}
我假设你的日期存储在DateTime变量中? 如果是这样,比较非常简单:
if (Birthday > DateRangeLower && Birthday < DateRangeUpper) {
// it's your birthday!
}
如果你喜欢,你可以用扩展方法封装它:
public static bool Between(this DateTime compareDate, DateTime startDate, DateTime endDate) {
return compareDate > startDate && compareDate < endDate;
}
那么你可以这样称呼它:
if (Birthday.Between(DateRangeLower, DateRangeUpper) {
// it's your birthday
}
更新 :如果您要忽略生日的年份以确定日期周年是否在范围内,请应用以下内容:
if (DateRangeLower.DayOfYear <= DateRangeUpper.DayOfYear &&
Birthday.DayOfYear > DateRangeLower.DayOfYear && Birthday.DayOfYear < DateRangeUpper.DayOfYear) {
// it's your birthday
// the days are within the date range (and the range is in a single year)
}
else if (DateRangeLower.DayOfYear > DateRangeUpper.DayOfYear &&
Birthday.DayOfYear < DateRangeLower.DayOfYear && Birthday.DayOfYear > DateRangeUpper.DayOfYear) {
// it's your birthday
// note, we're actually checking to see if the date is outside of the
// original date's days to handle the case where the dates span a year end boundary
// this only works if the dates are not more than 1 year apart
}
已更新答案以包含SLC提到的上限归一化。 这应该适用于那些人在29/02的情况下出生的情况。
DateTime birthday = new DateTime(2000, 2, 1);
DateTime min = new DateTime(2008, 12, 25);
DateTime max = new DateTime(2009, 3, 1);
DateTime nLower = new DateTime(min.Year, birthday.Month, birthday.Day);
DateTime nUpper = new DateTime(max.Year, birthday.Month, birthday.Day);
if (birthday.Year <= max.Year &&
((nLower >= min && nLower <= max) || (nUpper >= min && nUpper <= max)))
{
// Happy birthday
Console.WriteLine("Happy birthday");
}
现在一个处理当天出生的人的版本(29/02):
public static bool IsBirthdayInRange(
DateTime birthday, DateTime min, DateTime max)
{
var dates = new DateTime[] { birthday, min };
for (int i = 0; i < dates.Length; i++)
{
if (dates[i].Month == 2 && dates[i].Day == 29)
{
dates[i] = dates[i].AddDays(-1);
}
}
birthday = dates[0];
min = dates[1];
DateTime nLower = new DateTime(min.Year, birthday.Month, birthday.Day);
DateTime nUpper = new DateTime(max.Year, birthday.Month, birthday.Day);
if (birthday.Year <= max.Year &&
((nLower >= min && nLower <= max) || (nUpper >= min && nUpper <= max)))
{
return true;
}
return false;
}
链接地址: http://www.djcxy.com/p/54405.html
上一篇: How to determine if birthday or anniversary occurred during date range
下一篇: What is a simple and efficient way to find rows with time