简体   繁体   中英

Calculating difference between two DateTime objects in C#

I have two DateTime objects in C#, say birthDateTime and curDateTime.

Now, I want to calculate the year difference bewteen current datetime and someone's birthday. I want to do something like

int years = curDateTime- birthDateTime;
//If years difference is greater than 5 years, do something.
  if(years > 5)
    ....

The subtraction operator will result in a TimeSpan struct. However, the concept of "years" does not apply to timespans, since the number of days in a year is not constant.

TimeSpan span = curDateTime - birthDateTime;
if (span.TotalDays > (365.26 * 5)) { ... }

If you want anything more precise than this, you will have to inspect the Year/Month/Day of your DateTime structs manually.

Sounds like you are trying to calculate a person's age in the way people usually respond when asked for their age.

See Calculate age in C# for the solution.

You can use AddYears method and check the condition if the Year property.

var d3 = d1.AddYears(-d2.Year);

if ((d1.Year - d3.Year) > 5)
{
    var ok = true;
}

You will need to handle invalid years, eg 2010 - 2010 will cause an exception.

if (birthDateTime.AddYears(5) < curDateTime)
{
    // difference is greater than 5 years, do something...
}
DateTime someDate = DateTime.Parse("02/12/1979");
int diff = DateTime.Now.Year - someDate.Year;

This is it, no exceptions or anything...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM