如何找到2个日期和那个月份的名称与日期之间的差异? [英] How to find difference between 2 dates and name of that months with date?

查看:59
本文介绍了如何找到2个日期和那个月份的名称与日期之间的差异?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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;
    }
}

推荐答案

问题是Timespan不能用几个月(因为Timespan)与开始日期无关),Timespan是你减去两个DateTime值时得到的。



看看这个:使用Age:它与TimeSpan不同! [ ^ ] - 它应该做你想要的。
The problem is that a Timespan doesn't work with months (because a Timespan isn't related to a start date) and a Timespan is what you get when you subtract two DateTime values.

Have a look at this: Working with Age: it's not the same as a TimeSpan![^] - it should do what you want.


这篇关于如何找到2个日期和那个月份的名称与日期之间的差异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆