如何在c#中计算两个日期之间的月差?
c#中是否有相当于VB的DateDiff()方法。我需要找出相隔数年的两个日期之间的月差。文档说我可以像这样使用TimeSpan:
TimeSpan ts = date1 - date2;
但这里的数据是以天为单位的。我不想把这个数字除以30,因为不是每个月都是30天,而且两个操作数的值相差很大,所以我担心除以30可能会得到错误的值。
有什么建议吗?
如何在c#中计算两个日期之间的月差?
c#中是否有相当于VB的DateDiff()方法。我需要找出相隔数年的两个日期之间的月差。文档说我可以像这样使用TimeSpan:
TimeSpan ts = date1 - date2;
但这里的数据是以天为单位的。我不想把这个数字除以30,因为不是每个月都是30天,而且两个操作数的值相差很大,所以我担心除以30可能会得到错误的值。
有什么建议吗?
当前回答
简单快速的解决方案,计算2个日期之间的总月份。 如果你只想得到不同的月份,而不计算From date中的月份-只需从代码中删除+1。
public static int GetTotalMonths(DateTime From, DateTime Till)
{
int MonthDiff = 0;
for (int i = 0; i < 12; i++)
{
if (From.AddMonths(i).Month == Till.Month)
{
MonthDiff = i + 1;
break;
}
}
return MonthDiff;
}
其他回答
如果你只关心月份和年份,想要触及两个日期(例如你想要从JAN/2021到AGO/2022),你可以使用这个:
int numberOfMonths= (Year2 > Year1 ? ( Year2 - Year1 - 1) * 12 + (12 - Month1) + Month2 + 1 : Month2 - Month1 + 1);
例子:
Year1/Month1: 2021/10
Year2/Month2: 2022/08
numberOfMonths = 11;
或者同年:
Year1/Month1: 2021/10
Year2/Month2: 2021/12
numberOfMonths = 3;
如果你只想触碰其中一个,就去掉两个+ 1。
你可以这样做
if ( date1.AddMonths(x) > date2 )
LINQ的解决方案,
DateTime ToDate = DateTime.Today;
DateTime FromDate = ToDate.Date.AddYears(-1).AddDays(1);
int monthCount = Enumerable.Range(0, 1 + ToDate.Subtract(FromDate).Days)
.Select(x => FromDate.AddDays(x))
.ToList<DateTime>()
.GroupBy(z => new { z.Year, z.Month })
.Count();
有3种情况:同一年,前一年和其他年份。
如果日期不重要的话……
public int GetTotalNumberOfMonths(DateTime start, DateTime end)
{
// work with dates in the right order
if (start > end)
{
var swapper = start;
start = end;
end = swapper;
}
switch (end.Year - start.Year)
{
case 0: // Same year
return end.Month - start.Month;
case 1: // last year
return (12 - start.Month) + end.Month;
default:
return 12 * (3 - (end.Year - start.Year)) + (12 - start.Month) + end.Month;
}
}
除了所有给出的答案,我发现这段代码非常简单。DateTime。MinValue是1/1/1,我们必须从月,年和日减去1。
var timespan = endDate.Subtract(startDate);
var tempdate = DateTime.MinValue + timespan;
var totalMonths = (tempdate.Year - 1) * 12 + tempdate.Month - 1;
var totalDays = tempdate.Day - 1;
if (totalDays > 0)
{
totalMonths = totalMonths + 1;
}