如何计算两个日期之间的月数在C# [英] How to calculate the number of months between two dates in C#

查看:180
本文介绍了如何计算两个日期之间的月数在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在做这个

datediff = (date1 - DateOfDeposit).TotalDays;

但这给了没有。

推荐答案

假设您需要全部个月的数量,我认为这应该工作(不确定什么角落的情况下,这不能处理,但不能想到任何偏离我的头顶):

Assuming you want the number of whole months, I think this should work (not sure what corner-cases this doesn't handle, but can't think of any off the top of my head):

12 * (date1.Year - DateOfDeposit.Year) + (date1.Month - DateOfDeposit.Month)

您可以随时使用DateTime.Day添加任何分数组件,但不清楚如何精确定义(1月29日和2月27日之间有多少月?)。

You could always add any fractional component with DateTime.Day, but it's not clear how that should precisely be defined (how many months are between Jan 29 and Feb 27?).

如果你做了很多日期时间处理,Jon Skeet的Noda Time库(他在他的答案中提到)是一个不错的选择。

If you're doing a lot of date-time handling, Jon Skeet's Noda Time library (that he mentions in his answer) is a good choice.

这篇关于如何计算两个日期之间的月数在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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