当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - Month difference between 2 dates

问题描述:

I am trying to calculate MONTH difference between one date column and today. Do we have any method in csharp like monthdiff or datediff to achieve this functionlaity? Issue with my code is if submission date year is different then it breaks.

bool isDateAccepted = ((SubmissionDate.Month - DateTime.Now.Month) < 6)

网友答案:

You could always add 6 months to the submission date, and compare it to the current date.

bool isDateAccepted = (submissionDate.AddMonths(6) > DateTime.Now);
网友答案:

Don't directly compare the Month variables, as it will break when the month number "wraps" as you have noticed.

Instead, subtract the DateTime objects to get a TimeSpan then use that TotalDays property:

bool isDateAccepted = ((SubmissionDate - DateTime.Now).TotalDays < 6 * 30)

TimeSpan doesn't consider Months, so you'll have to define an average number of days in order to check the number for months passed.

网友答案:

You could calculate the total months and subtract them:

public int MonthDifference(Date a, Date b)
{
   int totalMonthsA = a.Year*12 + a.Month;
   int totalMonthsB = b.Year*12 + b.Month;
   return totalMonthsA - totalMonthsB;
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: