Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if birthday or anniversary occurred during date range

Tags:

Given I have a birthday/anniversary DateTime, how can I determine if that date occurred during a specific date range? For example,

Birthday = 1/2/2000
Date Range = 12/25/2008 - 1/3/2009

I need a method to determine whether or not this person's birthday happened during that date range - preferably in C#.

I first went about changing the year of the birthday DateTime to match the date range, then just check if the "new" birthday DateTime is between the start and end date of the date range... but when the date range spans different years, like in my example above - I had to add a nasty if statement. Is there no better way?

like image 223
davekaro Avatar asked Mar 31 '10 14:03

davekaro


2 Answers

Ok, here's my take

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; } 
like image 69
Haas Avatar answered Oct 07 '22 02:10

Haas


I'm assuming that your dates are stored in DateTime variables? If so, the comparison is pretty straight forward:

if (Birthday > DateRangeLower && Birthday < DateRangeUpper) {     // it's your birthday! } 

You can encapsulate this in an extension method if you like:

public static bool Between(this DateTime compareDate, DateTime startDate, DateTime endDate) {     return compareDate > startDate && compareDate < endDate; } 

then you can call it like such:

if (Birthday.Between(DateRangeLower, DateRangeUpper) {     // it's your birthday } 

Update: If you want to ignore the birthday's year part to determine if the anniversary of the date is within the range, apply the following:

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 } 
like image 40
Dexter Avatar answered Oct 07 '22 00:10

Dexter