如何在c#中计算两个日期之间的月差?
c#中是否有相当于VB的DateDiff()方法。我需要找出相隔数年的两个日期之间的月差。文档说我可以像这样使用TimeSpan:
TimeSpan ts = date1 - date2;
但这里的数据是以天为单位的。我不想把这个数字除以30,因为不是每个月都是30天,而且两个操作数的值相差很大,所以我担心除以30可能会得到错误的值。
有什么建议吗?
如何在c#中计算两个日期之间的月差?
c#中是否有相当于VB的DateDiff()方法。我需要找出相隔数年的两个日期之间的月差。文档说我可以像这样使用TimeSpan:
TimeSpan ts = date1 - date2;
但这里的数据是以天为单位的。我不想把这个数字除以30,因为不是每个月都是30天,而且两个操作数的值相差很大,所以我担心除以30可能会得到错误的值。
有什么建议吗?
当前回答
public static int PayableMonthsInDuration(DateTime StartDate, DateTime EndDate)
{
int sy = StartDate.Year; int sm = StartDate.Month; int count = 0;
do
{
count++;if ((sy == EndDate.Year) && (sm >= EndDate.Month)) { break; }
sm++;if (sm == 13) { sm = 1; sy++; }
} while ((EndDate.Year >= sy) || (EndDate.Month >= sm));
return (count);
}
这个解决方案是用于租金/订阅计算的,其中的差异并不意味着减法,它意味着这两个日期之间的跨度。
其他回答
一定是有人干的))
扩展方法返回给定日期之间的完整月数。无论以什么顺序接收日期,都会返回一个自然数。在“正确”答案中没有近似的计算。
/// <summary>
/// Returns the difference between dates in months.
/// </summary>
/// <param name="current">First considered date.</param>
/// <param name="another">Second considered date.</param>
/// <returns>The number of full months between the given dates.</returns>
public static int DifferenceInMonths(this DateTime current, DateTime another)
{
DateTime previous, next;
if (current > another)
{
previous = another;
next = current;
}
else
{
previous = current;
next = another;
}
return
(next.Year - previous.Year) * 12 // multiply the difference in years by 12 months
+ next.Month - previous.Month // add difference in months
+ (previous.Day <= next.Day ? 0 : -1); // if the day of the next date has not reached the day of the previous one, then the last month has not yet ended
}
但如果你仍然想要得到月份的小数部分,你只需要在回报中再加一项:
+(下一个。Day - previous.Day) / DateTime.DaysInMonth(previous. Day)年,previous.Month)
如果您想要完整月份的确切数目,总是正的(2000-01-15,2000-02-14返回0),则考虑完整月份是当您到达下个月的同一天时(类似于年龄计算)
public static int GetMonthsBetween(DateTime from, DateTime to)
{
if (from > to) return GetMonthsBetween(to, from);
var monthDiff = Math.Abs((to.Year * 12 + (to.Month - 1)) - (from.Year * 12 + (from.Month - 1)));
if (from.AddMonths(monthDiff) > to || to.Day < from.Day)
{
return monthDiff - 1;
}
else
{
return monthDiff;
}
}
编辑原因:旧代码在某些情况下不正确,如:
new { From = new DateTime(1900, 8, 31), To = new DateTime(1901, 8, 30), Result = 11 },
Test cases I used to test the function:
var tests = new[]
{
new { From = new DateTime(1900, 1, 1), To = new DateTime(1900, 1, 1), Result = 0 },
new { From = new DateTime(1900, 1, 1), To = new DateTime(1900, 1, 2), Result = 0 },
new { From = new DateTime(1900, 1, 2), To = new DateTime(1900, 1, 1), Result = 0 },
new { From = new DateTime(1900, 1, 1), To = new DateTime(1900, 2, 1), Result = 1 },
new { From = new DateTime(1900, 2, 1), To = new DateTime(1900, 1, 1), Result = 1 },
new { From = new DateTime(1900, 1, 31), To = new DateTime(1900, 2, 1), Result = 0 },
new { From = new DateTime(1900, 8, 31), To = new DateTime(1900, 9, 30), Result = 0 },
new { From = new DateTime(1900, 8, 31), To = new DateTime(1900, 10, 1), Result = 1 },
new { From = new DateTime(1900, 1, 1), To = new DateTime(1901, 1, 1), Result = 12 },
new { From = new DateTime(1900, 1, 1), To = new DateTime(1911, 1, 1), Result = 132 },
new { From = new DateTime(1900, 8, 31), To = new DateTime(1901, 8, 30), Result = 11 },
};
能够计算以月为单位的两个日期之间的差异是一件非常符合逻辑的事情,并且在许多业务应用程序中都需要它。这里的几个程序员提供了一些评论,比如“2010年5月1日”和“2010年6月16日”之间的月份有什么不同,2010年12月31日和2011年1月1日之间的月份有什么不同?——无法理解商业应用的基本知识。
以下是以上2条评论的答案——2010年5月1日至2010年6月16日之间的月数为1个月,2010年12月31日至2011年1月1日之间的月数为0。如上面的程序员所建议的那样,将它们计算为1.5个月零1秒是非常愚蠢的。
从事过信用卡、抵押贷款处理、税务处理、租金处理、每月利息计算和其他各种业务解决方案的人会同意这一点。
问题是c#或VB中不包含这样的函数。NET。Datediff只考虑年份或月份组件,因此实际上是无用的。
下面是一些现实生活中的例子,你需要正确地计算月份:
你从2月18日到8月23日住在短租公寓里。你在那里呆了几个月?答案很简单——6个月
你有一个银行账户,每月月底计算并支付利息。您在6月10日存入,同年10月29日取出。你有多少个月的利息?非常简单的答案——4个月(额外的日子也没关系)
在业务应用中,大多数情况下,当您需要计算月份时,是因为您需要根据人类计算时间的方式了解“完整的”月份;而不是基于一些抽象/无关的想法。
我对两个日期之间总月差的理解有一个整数部分和一个小数部分(日期很重要)。
积分部分是整个月的差额。
对我来说,小数部分是开始月份和结束月份之间一天的百分比(到一个月的全部天数)的差值。
public static class DateTimeExtensions
{
public static double TotalMonthsDifference(this DateTime from, DateTime to)
{
//Compute full months difference between dates
var fullMonthsDiff = (to.Year - from.Year)*12 + to.Month - from.Month;
//Compute difference between the % of day to full days of each month
var fractionMonthsDiff = ((double)(to.Day-1) / (DateTime.DaysInMonth(to.Year, to.Month)-1)) -
((double)(from.Day-1)/ (DateTime.DaysInMonth(from.Year, from.Month)-1));
return fullMonthsDiff + fractionMonthsDiff;
}
}
有了这个扩展,这些是结果:
2/29/2000 TotalMonthsDifference 2/28/2001 => 12
2/28/2000 TotalMonthsDifference 2/28/2001 => 12.035714285714286
01/01/2000 TotalMonthsDifference 01/16/2000 => 0.5
01/31/2000 TotalMonthsDifference 01/01/2000 => -1.0
01/31/2000 TotalMonthsDifference 02/29/2000 => 1.0
01/31/2000 TotalMonthsDifference 02/28/2000 => 0.9642857142857143
01/31/2001 TotalMonthsDifference 02/28/2001 => 1.0
你可以使用野田时间https://nodatime.org/
LocalDate start = new LocalDate(2010, 1, 5);
LocalDate end = new LocalDate(2012, 6, 1);
Period period = Period.Between(start, end, PeriodUnits.Months);
Console.WriteLine(period.Months);