开发者

Calculate difference between two dates in form `X years, Y months, Z week, A day` [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

How开发者_如何转开发 to get difference between two dates in Year/Month/Week/Day?

How do i calculate exact difference between to date including years, days, moths, weeks. Just like windows calculator does. ?

And represent like this 1 years, 1 months, 1 week, 1 day


I don't believe there's anything built into .NET itself which does this in a useful way. TimeSpan (which you'd get from date2 - date1) doesn't have the concept of months etc - it's just a duration in ticks, effectively.

You can use Noda Time for this, but it's not quite finished yet. The period calcuation part may well change further... I'm not sure yet. Let me know if you'd like a Noda Time code sample.

Also be aware that arithmetic using dates is fundamentally tricky. Sometimes it's hard to work out what the right answer should even be...


Try this.

TimeSpan span = endDate - startDate;
//span.TotalDays gives days

As for months, years and weeks one would like to know whether you need a Math.Floor or Math.Ceil


Found this on MSDN
For your case you can use the first method System.TimeSpan to get the differnce in the specified format.

System.DateTime date1 = new System.DateTime(1996, 6, 3, 22, 15, 0);
System.DateTime date2 = new System.DateTime(1996, 12, 6, 13, 2, 0);
System.DateTime date3 = new System.DateTime(1996, 10, 12, 8, 42, 0);

// diff1 gets 185 days, 14 hours, and 47 minutes.
System.TimeSpan diff1 = date2.Subtract(date1);

// date4 gets 4/9/1996 5:55:00 PM.
System.DateTime date4 = date3.Subtract(diff1);

// diff2 gets 55 days 4 hours and 20 minutes.
System.TimeSpan diff2 = date2 - date3;

// date5 gets 4/9/1996 5:55:00 PM.
System.DateTime date5 = date1 - diff2;

http://msdn.microsoft.com/en-us/library/8ysw4sby(v=VS.80).aspx#Y913

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜