如何找到两个日期之间的年份和月份区别?
问题描述:
DateTime dayStart;
DateTime dateEnd;
TimeSpan ts = dateEnt - dateStart;
打印:...年(S)和...月(S)
Print : ... Year(s) and ... Month(s)
我该怎么计算呢?
的.NET Framework 2.0结果$ b $#BC
.net framework 2.0
c#
asp.net项目。
asp.net project.
答
这要看你要计算什么。
您不能转换在时间跨度
来精确年和月的值,它的年和月长而变化。你可以计算近似年和月是这样的:
You can't translate the value in a TimeSpan
to exact years and months, as the length of years and months varies. You can calculate approximate years and months like this:
int years = ts.Days / 365;
int months = (ts.Days % 365) / 31;
如果你想准确的区别,你要比较的DateTime
值。
If you want the exact difference, you have to compare the DateTime
values.