1

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

Community
  • 1
  • 1
Code0987
  • 2,598
  • 3
  • 33
  • 51

3 Answers3

1

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...

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • I'm getting 404 error while opening `http://noda-time.sourceforge.net/` – Code0987 Jul 10 '11 at 06:29
  • @Neeraj: Gah, sorry, it's too early for me. I've fixed the link :) – Jon Skeet Jul 10 '11 at 06:30
  • @Jon: you may need to repeat your answer you have provided here. http://stackoverflow.com/questions/1083955/how-to-get-difference-between-two-dates-in-year-month-week-day – naveen Jul 10 '11 at 06:38
0

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

naveen
  • 53,448
  • 46
  • 161
  • 251
  • As per my comment on Peter's answer, that won't help for weeks, months and years. – Jon Skeet Jul 10 '11 at 06:22
  • @Jon Skeet: if i knew you were around, I wouldn't have even answered :) I just started on getting years and then i realized the complexities. – naveen Jul 10 '11 at 06:29
0

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

Saanch
  • 1,814
  • 1
  • 24
  • 38