两个日期之间的月差
Month difference between 2 dates
我正在尝试计算一个日期列与今天之间的 MONTH 差异。我们在 csharp 中有没有像 monthdiff 或 datediff 这样的方法来实现这个功能?我的代码的问题是,如果提交日期年份不同,则会中断。
bool isDateAccepted = ((SubmissionDate.Month - DateTime.Now.Month) < 6)
不要直接比较 Month
变量,因为它会在月数 "wraps" 时中断,正如您所注意到的。
相反,减去 DateTime
对象得到 TimeSpan
然后使用 that TotalDays
属性:
bool isDateAccepted = ((SubmissionDate - DateTime.Now).TotalDays < 6 * 30)
TimeSpan
不考虑 Months
,因此您必须定义平均天数才能检查过去的月数。
您可以计算总月数并减去它们:
public int MonthDifference(Date a, Date b)
{
int totalMonthsA = a.Year*12 + a.Month;
int totalMonthsB = b.Year*12 + b.Month;
return totalMonthsA - totalMonthsB;
}
您总是可以将提交日期加上 6 个月,并将其与当前日期进行比较。
bool isDateAccepted = (submissionDate.AddMonths(6) > DateTime.Now);
这是一个太晚的答案,正如我检查的那样,没有人像我们在 TimeSpan.TotalDays
中那样回答月份的确切分数。
例如 20-01-2021
和 20-03-2021
之间的总月数的结果是什么?
我想它应该是 2.0xx
,但如果您将 2 月视为 30 天,您会得到不同的答案“1.8xx
或其他”
所以我根据所选日期之间每个月的天数进行了计算。
- 首先,我得到了所选两个日期之间的天数列表,如 @mqp answer
- 然后按月分组计算
代码:
public static double GetTotalMonths(this DateTimeOffset firstDate, DateTimeOffset thru)
{
var days = firstDate.EachDayTill(thru).ToList();
return days.GroupBy(d => new {d.Month, d.Year,})
.Sum(g => (g.Count() * 1.00) / (DateTime.DaysInMonth(g.Key.Year, g.Key.Month) * 1.00));
}
public static IEnumerable<DateTimeOffset> EachDayTill(this DateTimeOffset from, DateTimeOffset thru)
{
for (var day = new DateTimeOffset(from.Date, TimeSpan.Zero); day.Date <= thru.Date; day = day.AddDays(1))
yield return day;
}
我正在尝试计算一个日期列与今天之间的 MONTH 差异。我们在 csharp 中有没有像 monthdiff 或 datediff 这样的方法来实现这个功能?我的代码的问题是,如果提交日期年份不同,则会中断。
bool isDateAccepted = ((SubmissionDate.Month - DateTime.Now.Month) < 6)
不要直接比较 Month
变量,因为它会在月数 "wraps" 时中断,正如您所注意到的。
相反,减去 DateTime
对象得到 TimeSpan
然后使用 that TotalDays
属性:
bool isDateAccepted = ((SubmissionDate - DateTime.Now).TotalDays < 6 * 30)
TimeSpan
不考虑 Months
,因此您必须定义平均天数才能检查过去的月数。
您可以计算总月数并减去它们:
public int MonthDifference(Date a, Date b)
{
int totalMonthsA = a.Year*12 + a.Month;
int totalMonthsB = b.Year*12 + b.Month;
return totalMonthsA - totalMonthsB;
}
您总是可以将提交日期加上 6 个月,并将其与当前日期进行比较。
bool isDateAccepted = (submissionDate.AddMonths(6) > DateTime.Now);
这是一个太晚的答案,正如我检查的那样,没有人像我们在 TimeSpan.TotalDays
中那样回答月份的确切分数。
例如 20-01-2021
和 20-03-2021
之间的总月数的结果是什么?
我想它应该是 2.0xx
,但如果您将 2 月视为 30 天,您会得到不同的答案“1.8xx
或其他”
所以我根据所选日期之间每个月的天数进行了计算。
- 首先,我得到了所选两个日期之间的天数列表,如 @mqp answer
- 然后按月分组计算
代码:
public static double GetTotalMonths(this DateTimeOffset firstDate, DateTimeOffset thru)
{
var days = firstDate.EachDayTill(thru).ToList();
return days.GroupBy(d => new {d.Month, d.Year,})
.Sum(g => (g.Count() * 1.00) / (DateTime.DaysInMonth(g.Key.Year, g.Key.Month) * 1.00));
}
public static IEnumerable<DateTimeOffset> EachDayTill(this DateTimeOffset from, DateTimeOffset thru)
{
for (var day = new DateTimeOffset(from.Date, TimeSpan.Zero); day.Date <= thru.Date; day = day.AddDays(1))
yield return day;
}