有时我们需要计算两个时间点相差的年份和月份,比如从2022年1月到2023年3月,相差多少年多少月。
TimeSpan(链接)只提供了总计天数、总计小时、总计分钟等等的结果,并没有提供总计年、总计月(由于它表示一个不引用特定起点或终点的常规间隔,因此不能用年和月来表示,这两者都有可变的天数。)。那么我们应该如何去计算呢?可以使用一个DateTime.MinValue
代码如下:

private static void Calculation(int year, int month)
{
    var firstTime = new DateTime(year, month, 1);
    DateTime time;
    if (firstTime <= DateTime.Now)
    {
        time = DateTime.MinValue + (DateTime.Now - firstTime);
    }
    else
    {
        time = DateTime.MinValue + (firstTime - DateTime.Now);
    }
    Console.WriteLine($"Total Month: {(time.Year - 1) * 12 + time.Month - 1}");
    //DateTime.MinValue=1 year 1 month 1 day, so we need to year-1,month-1,day-1
    Console.WriteLine($"Year:{time.Year - 1},Month:{time.Month - 1},Day:{time.Day - 1}");
}

由于DateTime.MinValue=1年1月1日,所以这里年月日的最终结果都要减1。

示例代码

TimeSpanTestDemo

参考资料

TimeSpan Years and Months

学习技术最好的文档就是官方文档,没有之一。
还有学习资料Microsoft Learn、【CSharp Learn】、My Note
如果,你希望更容易地发现我的新博客,不妨点击一下【关注】。