如何显示两个日期之间的差异为00Y 00M [英] How to display difference between two dates as 00Y 00M
本文介绍了如何显示两个日期之间的差异为00Y 00M的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我可以在简单减法的时间段上做基本的算术,这不会考虑到月份,闰年等不同的长度。
感谢任何帮助。
解决方案
因为底线表示是从AD公元1月1日凌晨12:00开始以100纳秒的刻度进行测量的,所以减法会十分正确地处理闰年;
DateTime date1 = ...
DateTime date2 = ...
// date2必须在date1
TimeSpan差异= date2.Subtract(date1);
DateTime age = new DateTime(tsAge.Ticks);
int years = age.Years - 1;
int months = age.Month - 1;
Console.WriteLine({0} Y,{1} M,年,月);
Given two DateTimes in C#, how can I display the difference in years and months?
I can do basic arithmatic on the timespan that comes from a simple subtraction but this won't take into account the differing lengths of months, leap years etc.
Thanks for any help.
解决方案
Because the underlying representation is measured in 100-nanosecond ticks since 12:00 midnight, January 1, 1 A.D., a subtraction will handle leap years etc. quite correctly:
DateTime date1 = ...
DateTime date2 = ...
// date2 must be after date1
TimeSpan difference = date2.Subtract(date1);
DateTime age=new DateTime(tsAge.Ticks);
int years = age.Years - 1;
int months = age.Month - 1;
Console.WriteLine("{0}Y, {1}M", years, months);
这篇关于如何显示两个日期之间的差异为00Y 00M的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文