Determine if it has been 6 months since birthday in c# - c#

My application needs to adjust a clients current age by +0.5 if it has been 6 months since their last birthday.
The code should look something like this, but how many ticks would there be in 6 months?
if (DateTime.Today - dateOfBirth.Date > new TimeSpan(6))
{
adjust = 0.5M;
}
else
{
adjust = 0M;
}
Thanks in advance

EDIT: You know what, actually? Since clearly what you really need is just to display the user's age to within 6 months, this is what you should really do.
static decimal GetApproximateAge(DateTime dateOfBirth) {
TimeSpan age = DateTime.Now - dateOfBirth;
/* a note on the line below:
* treating 182.5 days as equivalent to 6 months,
* reasoning that this will provide acceptable accuracy
* for ages below ~360 years
*
* (result will be 1 day off for roughly every 4 years;
* for a calculation of half-years to be inaccurate
* would take 4 [years] * ~90 [days] = ~360)
*/
// get age in units of 6 months
// desired behavior is not to add 0.5 until
// a full six months have elapsed since the user's last birthday --
// using Math.Floor to ensure this
double approxAgeInHalfYears = Math.Floor(age.TotalDays / 182.5);
// now convert this to years
// did it this way to restrict age to increments of 0.5
double approxAgeInYears = approxAgeInHalfYears * 0.5;
return Convert.ToDecimal(approxAgeInYears);
}
The above code includes a big comment explaining its own shortcomings, helpfully pointed out by David.
Now, here's yet another option. It's kind of ugly because it uses a loop; but it's also more rock-solid since it utilizes the DateTime.AddMonths method, which has the advantage of having already been tested and documented by Microsoft.
static decimal GetApproximateAge(DateTime dateOfBirth) {
DateTime now = DateTime.Now;
int birthYear = dateOfBirth.Year;
int lastYear = now.Year - 1;
// obviously, if the user's alive, he/she had a birthday last year;
// therefore he/she is at least this old
int minimumAgeInYears = lastYear - birthYear;
// now the question is: how much time has passed since then?
double actualAgeInYears = (double)minimumAgeInYears;
// for every six months that have elapsed since the user's birthday
// LAST year, add 0.5 to his/her age
DateTime birthDateLastYear = new DateTime(lastYear, 1, 1)
.AddDays(dateOfBirth.DayOfYear);
DateTime comparisonDate = birthDateLastYear
.AddMonths(6);
while (comparisonDate < now) {
actualAgeInYears += 0.5;
comparisonDate = comparisonDate.AddMonths(6);
}
return Convert.ToDecimal(actualAgeInYears);
}
This idea that people have been suggesting of checking dateOfBirth.AddMonths(6) is wrong. Since dateOfBirth is a DateTime, it represents the user's birth date, not their birth day.
What you want to check is if six months have elapsed since the user's last birthday--not the date they were born. Here's one way to do that:
DateTime lastBirthDay = GetLastBirthday(dateOfBirth);
if (DateTime.Today > lastBirthDay.AddMonths(6))
{
adjust = 0.5M;
}
else
{
adjust = 0M;
}
DateTime GetLastBirthday(DateTime dateOfBirth)
{
int currentYear = DateTime.Now.Year;
int birthMonth = dateOfBirth.Month;
int birthDay = dateOfBirth.Day;
// if user was born on Feb 29 and this year is NOT a leap year,
// we'll say the user's birthday this year falls on Feb 28
if (birthMonth == 2 && birthDay == 29 && !IsLeapYear(currentYear))
birthDay = 28;
DateTime birthdayThisYear = new DateTime(
currentYear,
birthMonth,
birthDay
);
if (DateTime.Today > birthdayThisYear)
return birthdayThisYear;
else
return birthdayThisYear.AddYears(-1);
}
bool IsLeapYear(int year) {
return year % 400 == 0 || (year % 4 == 0 && year % 100 != 0);
}

Why not if (dateOfBirth.Date.AddMonths(6) < DateTime.Today) instead?

long ticks = new DateTime(0).AddMonths(6).Ticks;
TimeSpan ts = new TimeSpan(ticks);

if (dateOfBirth.Date.AddMonths(6) < DateTime.Today)
{
age += 0.5;
}

I think you might be overcomplicating things:
DateTime displayDate = User.BirthDate; // User.BirthDate is a mock for however you get the birth date
if(DateTime.Now.AddMonths(-6) > displayDate)
{
// More than 6 Months have passed, so perform your logic to add .5 years
}

Something like this?
if (DateTime.Now.AddMonths(-6) > dateofBirth.Date)
{
dateOfBirth = dateOfBirth.AddMonths(6);
}

I think you actually want to know if it is half a year since their last birthday not six months (since months vary in length).
int daysDiff = DateTime.Now.DayOfYear - dayofBirth.DayOfYear;
if (daysDiff <0) daysDiff += 365;
double adjust = daysDiff > 365/2 ? 0.5 : 0.0;

DateTime today = DateTime.Today;
DateTime lastBirthday = dateOfBirth.Date.AddYears(today.Year - dateOfBirth.Year);
if (lastBirthday > today) lastBirthday = lastBirthday.AddYears(-1);
if (today > lastBirthday.AddMonths(6))
adjust = 0.5M;
else
adjust = 0M;

Related

Date Time and Formula Improvement C#

I got here a scenario where I input an information but the code does does not work. What happen is when I input 12/11/2015, the Address2Panel shows. Which is wrong because there no more date that I can input because Person A is born in 12/11/2015. The logic should Enter addresses for the past 5 years. But it goes wrong if the Birthdate gap is not lesser the 5 years from the current date.
Person A Birthday = 12/11/2015
Person A StartLiving = 12/11/2015 because its the day he/she was born.
Should not display Address2Panel
int CurrentDateInMonths = (((DateTime.Today.Year) * 12) + (DateTime.Today.Month));
static int AlienMonthsAtCurrentAddress = 0;
DateTime myDateTime;
//LivedHere = 12/11/2015
myDateTime = DateTime.Parse(LivedHere.Text);
AlienMonthsAtCurrentAddress = (CurrentDateInMonths - (((Convert.ToInt16(myDateTime.Year)) * 12) + Convert.ToInt16(myDateTime.Month)));
if (AlienMonthsAtCurrentAddress < 60)
{
Address2Panel.Visible = true;//shows the Address2Panel
}
else
{
ClearAddress2Panel();//hides also the Address2Panel
}
Any suggestion how should I improve my formula and date time manipulation?
no need to convert date into months, subtract dates using DateTime.Subtract method :
From MSDN, DateTime.Subtract Method subtracts the specified date and time from this instance.It returns a TimeSpan object which has a property Days
static int AlienMonthsAtCurrentAddress = 0;
try
{
DateTime myDateTime;
myDateTime = DateTime.Parse(LivedHere.Text);
// If you don't wish to subtract from today's date use required date in place of DateTime.Now
TimeSpan span = DateTime.Now.Subtract ( myDateTime );
if (span.Days < 60)
{
Address2Panel.Visible = true;//shows the Address2Panel
}
else
{
ClearAddress2Panel();//hides also the Address2Panel
}
}
catch { }
You could check years, months and days with a separately logic, and then get them all together:
DateTime date = new DateTime(2015,11,12)
DateTime input = getDate()
int years = input.Year - date.Year - 1
years += If(input.Month > date.Month, 1, 0)
years += If(input.Month = date.Month AndAlso input.Day >= date.Day, 1, 0)
This will output the exact number of years between two days (truncating the resulting integer). You'll just have to compare it to 5, in your case

Date algorithm - Add days without considering leap years

The system I'm working on is built and configured in such a way, where users cannot choose leap years when setting up a recurring payment. This results in all the date-math behind the scenes having to ignore leap years. (I didn't choose this, but this is how it was written)
I have to write a method that takes in a DateTime value, and adds days to the date, ignoring leap years, which essentially means ignoring Feb 29th and pretending it doesn't exist.
For example, If I'm adding 365 days to 1/1/2016, that should result in 1/1/2017, not 12/31/2016.
I'm using .NET, so I can make use of DateTime.IsLeapYear, and other helper methods.
This is a work in progress, and here is what I have so far. I started taking a simpler route, and I'm now realizing that it's going to require a more complex algorithm.
public static DateTime AddDaysToDateWithLeapYearConsideration(DateTime date, int daysToAdd)
{
// Nothing to do
if (daysToAdd == 0)
{
return date;
}
// NOTE: This is an invalid approach; using DateTime.AddDays will take leap years into account
DateTime dateWithAddedDays = date.AddDays(daysToAdd);
const int FEB_28_DAY_OF_YEAR = 59;
int daysToSubtractForLeapYearConsideration = 0;
// The year is a leap year, which is under the feb 28 day threshold, and we're adding enough days to push it over the feb 28 day threshold
// This will result in .NET taking into account the feb 29th (the leap year day), but we have to subtract that leap year day since the system doesn't take feb 29th into account
if (DateTime.IsLeapYear(date.Year) && date.DayOfYear < FEB_28_DAY_OF_YEAR && (date.DayOfYear + daysToAdd > FEB_28_DAY_OF_YEAR))
{
daysToSubtractForLeapYearConsideration++;
}
// The resulting date (after the days are added or subtracted) is a leap year, whose day is past the feburary 28 day threshold, and it's not the same year as the date (i.e. it spans across "n" years)
if (DateTime.IsLeapYear(dateWithAddedDays.Year) && dateWithAddedDays.DayOfYear > FEB_28_DAY_OF_YEAR && dateWithAddedDays.Year != date.Year)
{
daysToSubtractForLeapYearConsideration++;
}
// We determined if the original date should be leap year considered, as well as the resulting date/year with the days added. Now see if there are any years in between
// that we should consider
bool isThereAYearRangeThatWeNeedToEvaluateLeapYearsFor = Math.Abs(date.Year - dateWithAddedDays.Year) > 0;
if (isThereAYearRangeThatWeNeedToEvaluateLeapYearsFor)
{
for (int leapYearEvalIndex = Math.Min(date.Year, dateWithAddedDays.Year); leapYearEvalIndex <= Math.Max(date.Year, dateWithAddedDays.Year); leapYearEvalIndex++)
{
bool isYearPartOfTheYearsThatWeveAlreadyChecked = leapYearEvalIndex == date.Year || leapYearEvalIndex == dateWithAddedDays.Year;
if (!isYearPartOfTheYearsThatWeveAlreadyChecked && DateTime.IsLeapYear(leapYearEvalIndex))
{
daysToSubtractForLeapYearConsideration++;
}
}
}
DateTime dateResult = date.AddDays(daysToAdd - daysToSubtractForLeapYearConsideration);
// The system does not allow 2/29 days, hence all this crazy date math
if (dateResult.Month == 2 && dateResult.Day == 29)
{
dateResult = dateResult.AddDays(1);
}
return dateResult;
}
The logic has to take into account negative numbers as well (i.e. subtracting), which the above code fails on.
The above code by no means works, but I wanted to demonstrate that I'm trying to tackle the problem, and not simply asking without having tried anything.
Edit
I've come up with an algorithm pretty close to David's approach. (I wrote it, and then came back to StackOverflow to check responses).
public static DateTime AddDaysToDateWithLeapYearConsideration(DateTime date, int daysToAdd)
{
// Nothing to do
if (daysToAdd == 0)
{
return date;
}
DateTime dateResult = date;
// Are we adding or subtracting
bool areWeAddingDays = daysToAdd > 0;
int daysToAccountForInRegardToLeapYearDates = 0,
absDaysToAdd = Math.Abs(daysToAdd);
for (int i = 1; i <= absDaysToAdd; i++)
{
dateResult = dateResult.AddDays(areWeAddingDays ? 1 : -1);
if (dateResult.Month == 2 && dateResult.Day == 29)
{
daysToAccountForInRegardToLeapYearDates++;
}
}
dateResult = dateResult.AddDays(areWeAddingDays ? daysToAccountForInRegardToLeapYearDates : -daysToAccountForInRegardToLeapYearDates);
return dateResult;
}
Here is an extension method that works. Will also work if you're adding or subtracting enough days to span multiple leap years.
public static DateTime AddDaysWithoutLeapYear(this DateTime input, int days)
{
var output = input;
if (days != 0)
{
var increment = days > 0 ? 1 : -1; //this will be used to increment or decrement the date.
var daysAbs = Math.Abs(days); //get the absolute value of days to add
var daysAdded = 0; // save the number of days added here
while (daysAdded < daysAbs)
{
output = output.AddDays(increment);
if (!(output.Month == 2 && output.Day == 29)) //don't increment the days added if it is a leap year day
{
daysAdded++;
}
}
}
return output;
}
Might need some more testing, but without using the DateTime Add... functions or too much looping, a possible custom implementation:
public static DateTime AddDaysToDateWithLeapYearConsideration(DateTime date, int daysToAdd)
{
int year = date.Year + daysToAdd / 365, month = date.Month - 1, dir = Math.Sign(daysToAdd);
daysToAdd = (daysToAdd % 365) + date.Day;
int[] months = {31,28,31,30,31,30,31,31,30,31,30,31};
while(daysToAdd > months[month] || daysToAdd < 0){
if(dir ==1) daysToAdd -= months[month];
month += dir;
if(month == 12 || month == -1){
year += dir;
month = dir == -1 ? 11 : 0;
}
if(dir ==-1) daysToAdd += months[month]; //for reverse direction, add previous month
}
return new DateTime(year, ++month,daysToAdd);
}

Determine most recent and next Payday (alternating Fridays)

I am very close to getting this to work and hope someone here can help push the ball over the top of the hill. In C#, I need to get the most recent Payday and the next Payday from today's date (and will eventually expand this to find any pay date in the company's history). Payday occurs every other Friday. I am using a baseline date from history to find my pay dates.
My assumption (please correct if I am wrong) is that I should always be able to divide my pay date by 14. If I cannot, then I must be on a non-pay week.
Here is what I have done thus far:
public DateTime GetNextPayDay()
{
DateTime myNow = DateTime.Now;
string myDay = myNow.DayOfWeek.ToString();
while (myDay != "Friday")
{
myNow = myNow.AddDays(1);
myDay = myNow.DayOfWeek.ToString();
}
DateTime mySeedDate = DateTime.Parse("01/02/1970");
TimeSpan myTimeSpan = myNow.Subtract(mySeedDate);
int myDaysDifference = myTimeSpan.Days;
if (myDaysDifference % 14 == 0) // Problem is here
{
myNow = myNow.AddDays(7);
}
return myNow;
}
public DateTime GetLastPayDay()
{
DateTime myNow = DateTime.Now;
string myDay = myNow.DayOfWeek.ToString();
while (myDay != "Friday")
{
myNow = myNow.AddDays(-1);
myDay = myNow.DayOfWeek.ToString();
}
DateTime mySeedDate = DateTime.Parse("01/02/1970");
TimeSpan myTimeSpan = myNow.Subtract(mySeedDate);
int myDaysDifference = myTimeSpan.Days;
if (myDaysDifference % 14 == 0) // Problem is here
{
myNow = myNow.AddDays(-7);
}
return myNow;
}
Your issue is the
if (myDaysDifference % 14 == 0)
should be a not equal
if (myDaysDifference % 14 != 0)
in both methods.
Your logic is currently finding the previous Friday from now and then seeing if the difference between that and the first date is divisible by 14 and if so you are adding 7 days to it. This is incorrect as if the gap is divisible by 14 then myDay must be a payday. You only want to add 7 if myDaysDifference doesn't divide exactly by 14 as this would mean you have a Friday that isn't a pay day.

Date difference in years using C# [duplicate]

This question already has answers here:
How do I calculate someone's age based on a DateTime type birthday?
(74 answers)
Closed 6 years ago.
How can I calculate date difference between two dates in years?
For example: (Datetime.Now.Today() - 11/03/2007) in years.
I have written an implementation that properly works with dates exactly one year apart.
However, it does not gracefully handle negative timespans, unlike the other algorithm. It also doesn't use its own date arithmetic, instead relying upon the standard library for that.
So without further ado, here is the code:
DateTime zeroTime = new DateTime(1, 1, 1);
DateTime a = new DateTime(2007, 1, 1);
DateTime b = new DateTime(2008, 1, 1);
TimeSpan span = b - a;
// Because we start at year 1 for the Gregorian
// calendar, we must subtract a year here.
int years = (zeroTime + span).Year - 1;
// 1, where my other algorithm resulted in 0.
Console.WriteLine("Yrs elapsed: " + years);
Use:
int Years(DateTime start, DateTime end)
{
return (end.Year - start.Year - 1) +
(((end.Month > start.Month) ||
((end.Month == start.Month) && (end.Day >= start.Day))) ? 1 : 0);
}
We had to code a check to establish if the difference between two dates, a start and end date was greater than 2 years.
Thanks to the tips above it was done as follows:
DateTime StartDate = Convert.ToDateTime("01/01/2012");
DateTime EndDate = Convert.ToDateTime("01/01/2014");
DateTime TwoYears = StartDate.AddYears(2);
if EndDate > TwoYears .....
If you need it for knowing someone's age for trivial reasons then Timespan is OK but if you need for calculating superannuation, long term deposits or anything else for financial, scientific or legal purposes then I'm afraid Timespan won't be accurate enough because Timespan assumes that every year has the same number of days, same # of hours and same # of seconds).
In reality the length of some years will vary (for different reasons that are outside the scope of this answer). To get around Timespan's limitation then you can mimic what Excel does which is:
public int GetDifferenceInYears(DateTime startDate, DateTime endDate)
{
//Excel documentation says "COMPLETE calendar years in between dates"
int years = endDate.Year - startDate.Year;
if (startDate.Month == endDate.Month &&// if the start month and the end month are the same
endDate.Day < startDate.Day// AND the end day is less than the start day
|| endDate.Month < startDate.Month)// OR if the end month is less than the start month
{
years--;
}
return years;
}
var totalYears =
(DateTime.Today - new DateTime(2007, 03, 11)).TotalDays
/ 365.2425;
Average days from Wikipedia/Leap_year.
int Age = new DateTime((DateTime.Now - BirthDateTime).Ticks).Year;
To calculate the elapsed years (age), the result will be minus one.
var timeSpan = DateTime.Now - birthDateTime;
int age = new DateTime(timeSpan.Ticks).Year - 1;
Here is a neat trick which lets the system deal with leap years automagically. It gives an accurate answer for all date combinations.
DateTime dt1 = new DateTime(1987, 9, 23, 13, 12, 12, 0);
DateTime dt2 = new DateTime(2007, 6, 15, 16, 25, 46, 0);
DateTime tmp = dt1;
int years = -1;
while (tmp < dt2)
{
years++;
tmp = tmp.AddYears(1);
}
Console.WriteLine("{0}", years);
It's unclear how you want to handle fractional years, but perhaps like this:
DateTime now = DateTime.Now;
DateTime origin = new DateTime(2007, 11, 3);
int calendar_years = now.Year - origin.Year;
int whole_years = calendar_years - ((now.AddYears(-calendar_years) >= origin)? 0: 1);
int another_method = calendar_years - ((now.Month - origin.Month) * 32 >= origin.Day - now.Day)? 0: 1);
I implemented an extension method to get the number of years between two dates, rounded by whole months.
/// <summary>
/// Gets the total number of years between two dates, rounded to whole months.
/// Examples:
/// 2011-12-14, 2012-12-15 returns 1.
/// 2011-12-14, 2012-12-14 returns 1.
/// 2011-12-14, 2012-12-13 returns 0,9167.
/// </summary>
/// <param name="start">
/// Stardate of time period
/// </param>
/// <param name="end">
/// Enddate of time period
/// </param>
/// <returns>
/// Total Years between the two days
/// </returns>
public static double DifferenceTotalYears(this DateTime start, DateTime end)
{
// Get difference in total months.
int months = ((end.Year - start.Year) * 12) + (end.Month - start.Month);
// substract 1 month if end month is not completed
if (end.Day < start.Day)
{
months--;
}
double totalyears = months / 12d;
return totalyears;
}
public string GetAgeText(DateTime birthDate)
{
const double ApproxDaysPerMonth = 30.4375;
const double ApproxDaysPerYear = 365.25;
int iDays = (DateTime.Now - birthDate).Days;
int iYear = (int)(iDays / ApproxDaysPerYear);
iDays -= (int)(iYear * ApproxDaysPerYear);
int iMonths = (int)(iDays / ApproxDaysPerMonth);
iDays -= (int)(iMonths * ApproxDaysPerMonth);
return string.Format("{0} år, {1} måneder, {2} dage", iYear, iMonths, iDays);
}
I found this at TimeSpan for years, months and days:
DateTime target_dob = THE_DOB;
DateTime true_age = DateTime.MinValue + ((TimeSpan)(DateTime.Now - target_dob )); // Minimum value as 1/1/1
int yr = true_age.Year - 1;
If you're dealing with months and years you need something that knows how many days each month has and which years are leap years.
Enter the Gregorian Calendar (and other culture-specific Calendar implementations).
While Calendar doesn't provide methods to directly calculate the difference between two points in time, it does have methods such as
DateTime AddWeeks(DateTime time, int weeks)
DateTime AddMonths(DateTime time, int months)
DateTime AddYears(DateTime time, int years)
DateTime musteriDogum = new DateTime(dogumYil, dogumAy, dogumGun);
int additionalDays = ((DateTime.Now.Year - dogumYil) / 4); //Count of the years with 366 days
int extraDays = additionalDays + ((DateTime.Now.Year % 4 == 0 || musteriDogum.Year % 4 == 0) ? 1 : 0); //We add 1 if this year or year inserted has 366 days
int yearsOld = ((DateTime.Now - musteriDogum).Days - extraDays ) / 365; // Now we extract these extra days from total days and we can divide to 365
Works perfect:
internal static int GetDifferenceInYears(DateTime startDate)
{
int finalResult = 0;
const int DaysInYear = 365;
DateTime endDate = DateTime.Now;
TimeSpan timeSpan = endDate - startDate;
if (timeSpan.TotalDays > 365)
{
finalResult = (int)Math.Round((timeSpan.TotalDays / DaysInYear), MidpointRounding.ToEven);
}
return finalResult;
}
Simple solution:
public int getYearDiff(DateTime startDate, DateTime endDate){
int y = Year(endDate) - Year(startDate);
int startMonth = Month(startDate);
int endMonth = Month(endDate);
if (endMonth < startMonth)
return y - 1;
if (endMonth > startMonth)
return y;
return (Day(endDate) < Day(startDate) ? y - 1 : y);
}
This is the best code to calculate year and month difference:
DateTime firstDate = DateTime.Parse("1/31/2019");
DateTime secondDate = DateTime.Parse("2/1/2016");
int totalYears = firstDate.Year - secondDate.Year;
int totalMonths = 0;
if (firstDate.Month > secondDate.Month)
totalMonths = firstDate.Month - secondDate.Month;
else if (firstDate.Month < secondDate.Month)
{
totalYears -= 1;
int monthDifference = secondDate.Month - firstDate.Month;
totalMonths = 12 - monthDifference;
}
if ((firstDate.Day - secondDate.Day) == 30)
{
totalMonths += 1;
if (totalMonths % 12 == 0)
{
totalYears += 1;
totalMonths = 0;
}
}
Maybe this will be helpful for answering the question: Count of days in given year,
new DateTime(anyDate.Year, 12, 31).DayOfYear //will include leap years too
Regarding DateTime.DayOfYear Property.
The following is based off Dana's simple code which produces the correct answer in most cases. But it did not take in to account less than a year between dates. So here is the code that I use to produce consistent results:
public static int DateDiffYears(DateTime startDate, DateTime endDate)
{
var yr = endDate.Year - startDate.Year - 1 +
(endDate.Month >= startDate.Month && endDate.Day >= startDate.Day ? 1 : 0);
return yr < 0 ? 0 : yr;
}

How to calculate actual months difference (calendar year not approximation) between two given dates in C#?

Example: given two dates below, finish is always greater than or equal to start
start = 2001 Jan 01
finish = 2002 Mar 15
So from 2001 Jan 01 to the end of 2002 Feb
months = 12 + 2 = 14
For 2002 March
15/30 = 0.5
so grand total is 14.5 months difference.
It's very easy to work out by hand but how do I code it elegantly? At the moment I have the combination of a lot of if else and while loops to achieve what I want but I believe there are simpler solutions out there.
Update: the output needs to be precise (not approximation) for example:
if start 2001 Jan 01 and finish 2001 Apr 16, the output should be 1 + 1 + 1= 3 (for Jan, Feb and Mar) and 16 / 31 = 0.516 month, so the total is 3.516.
Another example would be if I start on 2001 Jul 5 and finish on 2002 Jul 10, the output should be 11 month up to the end of June 2002, and (31-5)/31 = 0.839 and 10/31 = 0.323 months, so the total is 11 + 0.839 + 0.323 = 12.162.
I extended Josh Stodola's code and Hightechrider's code:
public static decimal GetMonthsInRange(this IDateRange thisDateRange)
{
var start = thisDateRange.Start;
var finish = thisDateRange.Finish;
var monthsApart = Math.Abs(12*(start.Year - finish.Year) + start.Month - finish.Month) - 1;
decimal daysInStartMonth = DateTime.DaysInMonth(start.Year, start.Month);
decimal daysInFinishMonth = DateTime.DaysInMonth(finish.Year, finish.Month);
var daysApartInStartMonth = (daysInStartMonth - start.Day + 1)/daysInStartMonth;
var daysApartInFinishMonth = finish.Day/daysInFinishMonth;
return monthsApart + daysApartInStartMonth + daysApartInFinishMonth;
}
I gave an int answer before, and then realized what you asked for a more precise answer. I was tired, so I deleted and went to bed. So much for that, I was unable to fall asleep! For some reason, this question really bugged me, and I had to solve it. So here you go...
static void Main(string[] args)
{
decimal diff;
diff = monthDifference(new DateTime(2001, 1, 1), new DateTime(2002, 3, 15));
Console.WriteLine(diff.ToString("n2")); //14.45
diff = monthDifference(new DateTime(2001, 1, 1), new DateTime(2001, 4, 16));
Console.WriteLine(diff.ToString("n2")); //3.50
diff = monthDifference(new DateTime(2001, 7, 5), new DateTime(2002, 7, 10));
Console.WriteLine(diff.ToString("n2")); //12.16
Console.Read();
}
static decimal monthDifference(DateTime d1, DateTime d2)
{
if (d1 > d2)
{
DateTime hold = d1;
d1 = d2;
d2 = hold;
}
int monthsApart = Math.Abs(12 * (d1.Year-d2.Year) + d1.Month - d2.Month) - 1;
decimal daysInMonth1 = DateTime.DaysInMonth(d1.Year, d1.Month);
decimal daysInMonth2 = DateTime.DaysInMonth(d2.Year, d2.Month);
decimal dayPercentage = ((daysInMonth1 - d1.Day) / daysInMonth1)
+ (d2.Day / daysInMonth2);
return monthsApart + dayPercentage;
}
Now I shall have sweet dreams. Goodnight :)
What you want is probably something close to this ... which pretty much follows your explanation as to how to calculate it:
var startofd1 = d1.AddDays(-d1.Day + 1);
var startOfNextMonthAfterd1 = startofd1.AddMonths(1); // back to start of month and then to next month
int daysInFirstMonth = (startOfNextMonthAfterd1 - startofd1).Days;
double fraction1 = (double)(daysInFirstMonth - (d1.Day - 1)) / daysInFirstMonth; // fractional part of first month remaining
var startofd2 = d2.AddDays(-d2.Day + 1);
var startOfNextMonthAfterd2 = startofd2.AddMonths(1); // back to start of month and then to next month
int daysInFinalMonth = (startOfNextMonthAfterd2 - startofd2).Days;
double fraction2 = (double)(d2.Day - 1) / daysInFinalMonth; // fractional part of last month
// now find whole months in between
int monthsInBetween = (startofd2.Year - startOfNextMonthAfterd1.Year) * 12 + (startofd2.Month - startOfNextMonthAfterd1.Month);
return monthsInBetween + fraction1 + fraction2;
NB This has not been tested very well but it shows how to handle problems like this by finding well known dates at the start of months around the problem values and then working off them.
While loops for date time calculations are always a bad idea: see http://www.zuneboards.com/forums/zune-news/38143-cause-zune-30-leapyear-problem-isolated.html
Depending on how exactly you want your logic to work, this would at least give you a decent approximation:
// 365 days per year + 1 day per leap year = 1461 days every 4 years
// But years divisible by 100 are not leap years
// So 1461 days every 4 years - 1 day per 100th year = 36524 days every 100 years
// 12 months per year = 1200 months every 100 years
const double DaysPerMonth = 36524.0 / 1200.0;
double GetMonthsDifference(DateTime start, DateTime finish)
{
double days = (finish - start).TotalDays;
return days / DaysPerMonth;
}
One way to do this is that you'll see around quite a bit is:
private static int monthDifference(DateTime startDate, DateTime endDate)
{
int monthsApart = 12 * (startDate.Year - endDate.Year) + startDate.Month - endDate.Month;
return Math.Abs(monthsApart);
}
However, you want "partial months" which this doesn't give. But what is the point in comparing apples (January/March/May/July/August/October/December) with oranges (April/June/September/November) or even bananas that are sometimes coconuts (February)?
An alternative is to import Microsoft.VisualBasic and do this:
DateTime FromDate;
DateTime ToDate;
FromDate = DateTime.Parse("2001 Jan 01");
ToDate = DateTime.Parse("2002 Mar 15");
string s = DateAndTime.DateDiff (DateInterval.Month, FromDate,ToDate, FirstDayOfWeek.System, FirstWeekOfYear.System ).ToString();
However again:
The return value for
DateInterval.Month is calculated
purely from the year and month parts
of the arguments
[Source]
Just improved Josh's answer
static decimal monthDifference(DateTime d1, DateTime d2)
{
if (d1 > d2)
{
DateTime hold = d1;
d1 = d2;
d2 = hold;
}
decimal monthsApart = Math.Abs((12 * (d1.Year - d2.Year)) + d2.Month - d1.Month - 1);
decimal daysinStartingMonth = DateTime.DaysInMonth(d1.Year, d1.Month);
monthsApart = monthsApart + (1-((d1.Day - 1) / daysinStartingMonth));
// Replace (d1.Day - 1) with d1.Day incase you DONT want to have both inclusive difference.
decimal daysinEndingMonth = DateTime.DaysInMonth(d2.Year, d2.Month);
monthsApart = monthsApart + (d2.Day / daysinEndingMonth);
return monthsApart;
}
The answer works perfectly and while the terseness of the code makes it very small I had to break everything apart into smaller functions with named variables so that I could really understand what was going on... So, basically I just took Josh Stodola's code and Hightechrider's mentioned in Jeff's comment and made it smaller with comments explaining what was going on and why the calculations were being made, and hopefully this may help someone else:
[Test]
public void Calculate_Total_Months_Difference_Between_Two_Dates()
{
var startDate = DateTime.Parse( "10/8/1996" );
var finishDate = DateTime.Parse( "9/8/2012" ); // this should be now:
int numberOfMonthsBetweenStartAndFinishYears = getNumberOfMonthsBetweenStartAndFinishYears( startDate, finishDate );
int absMonthsApartMinusOne = getAbsMonthsApartMinusOne( startDate, finishDate, numberOfMonthsBetweenStartAndFinishYears );
decimal daysLeftToCompleteStartMonthPercentage = getDaysLeftToCompleteInStartMonthPercentage( startDate );
decimal daysCompletedSoFarInFinishMonthPercentage = getDaysCompletedSoFarInFinishMonthPercentage( finishDate );
// .77 + .26 = 1.04
decimal totalDaysDifferenceInStartAndFinishMonthsPercentage = daysLeftToCompleteStartMonthPercentage + daysCompletedSoFarInFinishMonthPercentage;
// 13 + 1.04 = 14.04 months difference.
decimal totalMonthsDifference = absMonthsApartMinusOne + totalDaysDifferenceInStartAndFinishMonthsPercentage;
//return totalMonths;
}
private static int getNumberOfMonthsBetweenStartAndFinishYears( DateTime startDate, DateTime finishDate )
{
int yearsApart = startDate.Year - finishDate.Year;
const int INT_TotalMonthsInAYear = 12;
// 12 * -1 = -12
int numberOfMonthsBetweenYears = INT_TotalMonthsInAYear * yearsApart;
return numberOfMonthsBetweenYears;
}
private static int getAbsMonthsApartMinusOne( DateTime startDate, DateTime finishDate, int numberOfMonthsBetweenStartAndFinishYears )
{
// This may be negative i.e. 7 - 9 = -2
int numberOfMonthsBetweenStartAndFinishMonths = startDate.Month - finishDate.Month;
// Absolute Value Of Total Months In Years Plus The Simple Months Difference Which May Be Negative So We Use Abs Function
int absDiffInMonths = Math.Abs( numberOfMonthsBetweenStartAndFinishYears + numberOfMonthsBetweenStartAndFinishMonths );
// Subtract one here because we are going to use a perecentage difference based on the number of days left in the start month
// and adding together the number of days that we've made it so far in the finish month.
int absMonthsApartMinusOne = absDiffInMonths - 1;
return absMonthsApartMinusOne;
}
/// <summary>
/// For example for 7/8/2012 there are 24 days left in the month so about .77 percentage of month is left.
/// </summary>
private static decimal getDaysLeftToCompleteInStartMonthPercentage( DateTime startDate )
{
// startDate = "7/8/2012"
// 31
decimal daysInStartMonth = DateTime.DaysInMonth( startDate.Year, startDate.Month );
// 31 - 8 = 23
decimal totalDaysInStartMonthMinusStartDay = daysInStartMonth - startDate.Day;
// add one to mark the day as being completed. 23 + 1 = 24
decimal daysLeftInStartMonth = totalDaysInStartMonthMinusStartDay + 1;
// 24 / 31 = .77 days left to go in the month
decimal daysLeftToCompleteInStartMonthPercentage = daysLeftInStartMonth / daysInStartMonth;
return daysLeftToCompleteInStartMonthPercentage;
}
/// <summary>
/// For example if the finish date were 9/8/2012 we've completed 8 days so far or .24 percent of the month
/// </summary>
private static decimal getDaysCompletedSoFarInFinishMonthPercentage( DateTime finishDate )
{
// for septebmer = 30 days in month.
decimal daysInFinishMonth = DateTime.DaysInMonth( finishDate.Year, finishDate.Month );
// 8 days divided by 30 = .26 days completed so far in finish month.
decimal daysCompletedSoFarInFinishMonthPercentage = finishDate.Day / daysInFinishMonth;
return daysCompletedSoFarInFinishMonthPercentage;
}
This solution calculates whole months and then adds the partial month based on the end of the time period. This way it always calculates full months between the dates' day-of-month and then calculates the partial month based on the number of remaining days.
public decimal getMonthDiff(DateTime date1, DateTime date2) {
// Make parameters agnostic
var earlyDate = (date1 < date2 ? date1 : date2);
var laterDate = (date1 > date2 ? date1 : date2);
// Calculate the change in full months
decimal months = ((laterDate.Year - earlyDate.Year) * 12) + (laterDate.Month - earlyDate.Month) - 1;
// Add partial months based on the later date
if (earlyDate.Day <= laterDate.Day) {
decimal laterMonthDays = DateTime.DaysInMonth(laterDate.Year, laterDate.Month);
decimal laterPartialMonth = ((laterDate.Day - earlyDate.Day) / laterMonthDays);
months += laterPartialMonth + 1;
} else {
var laterLastMonth = laterDate.AddMonths(-1);
decimal laterLastMonthDays = DateTime.DaysInMonth(laterLastMonth.Year, laterLastMonth.Month);
decimal laterPartialMonth = ((laterLastMonthDays - earlyDate.Day + laterDate.Day) / laterLastMonthDays);
months += laterPartialMonth;
}
return months;
}
The calculation below is one that is according the way the Dutch Tax Authority wants months calculated. This means that when the starts day is for example feb 22, march 23 should be result in something above 1 and not just something like 0.98.
private decimal GetMonthDiffBetter(DateTime date1, DateTime date2)
{
DateTime start = date1 < date2 ? date1 : date2;
DateTime end = date1 < date2 ? date2 : date1;
int totalYearMonths = (end.Year - start.Year) * 12;
int restMonths = end.Month - start.Month;
int totalMonths = totalYearMonths + restMonths;
decimal monthPart = (decimal)end.Day / (decimal)start.Day;
return totalMonths - 1 + monthPart;
}`
This should get you where you need to go:
DateTime start = new DateTime(2001, 1, 1);
DateTime finish = new DateTime(2002, 3, 15);
double diff = (finish - start).TotalDays / 30;
the framework as a TimeSpan object that is a result of subtracting two dates.
the subtraction is already considering the various option of February(28/29 days a month) so in my opinion this is the best practice
after you got it you can format it the way you like best
DateTime dates1 = new DateTime(2010, 1, 1);
DateTime dates2 = new DateTime(2010, 3, 15);
var span = dates1.Subtract(dates2);
span.ToString("your format here");
private Double GetTotalMonths(DateTime future, DateTime past)
{
Double totalMonths = 0.0;
while ((future - past).TotalDays > 28 )
{
past = past.AddMonths(1);
totalMonths += 1;
}
var daysInCurrent = DateTime.DaysInMonth(future.Year, future.Month);
var remaining = future.Day - past.Day;
totalMonths += ((Double)remaining / (Double)daysInCurrent);
return totalMonths;
}

Categories