1

Possible Duplicate:
Converting Days into Human Readable Duration Text
How do I calculate difference in years and months given a start and end

I use (end date - start date).TotalDays it returns total days. For example, 145 days

But I don't want total days.

It is possible to convert 145 days to 3 months and 25 days something like this.

Community
  • 1
  • 1
aratn0n
  • 553
  • 3
  • 5
  • 17

6 Answers6

4

A bit harder than it initially seems...

I suppose you could do something like this, which has the advantage of counting actual calendar months rather than estimating months to be 30days or similar.

var now = DateTime.Now;
var future = DateTime.Now.AddDays(new Random().NextDouble() * 365);
//dates above for example only

var xx = Enumerable.Range(0,int.MaxValue)
        .Select(i => new{numMonths = i, date = now.AddMonths(i)})
        .TakeWhile(x => x.date < future)
        .Last();
var remainingDays = (future - xx.date).TotalDays;
Console.WriteLine("{0} months and {1} days",xx.numMonths,remainingDays);
spender
  • 117,338
  • 33
  • 229
  • 351
1

if you assume a month to be 30 days, this below might help.

var start = DateTime.Today;

var end = DateTime.Today.AddDays(99);

var timeSpan = end.Subtract(start);

var months = (int)timeSpan.TotalDays / 30;

var days = timeSpan.TotalDays % 30;

var str = string.Format("{0} months, {1} days", months, days);
scartag
  • 17,548
  • 3
  • 48
  • 52
0

To overcome the number of days problem in a month, just look at the years and months

DateTime d1 = New DateTime(2002, 1, 1);
DateTime d2 = New DateTime(2000, 10, 1);
int years = Math.Abs((d1.Year - d2.Year));
int months = ((years  * 12)  + Math.Abs((d1.Month - d2.Month)));
Peter
  • 27,590
  • 8
  • 64
  • 84
0

The difference of two DateTime objects results in a TimeSpan object. Since the time spanned by a month is not consistent among months, how would a TimeSpan object be represented by a number of months?

In order to calculate the number of months between two dates, you'd need to know the start date and end date ahead of time so you can calculate the actual number of months (keeping in mind leap years, etc.) between them.

qxn
  • 17,162
  • 3
  • 49
  • 72
0

If you want years, months, days:

  1. Years = max number of years you can subtract from end date such that the result is still > start date.
  2. Months = max number of months you can subtract from the previous result such that the result is still > start date.
  3. Days = number of days between previous result and start date.
mbeckish
  • 10,485
  • 5
  • 30
  • 55
-3

Try use the time span to string...

Chen Kinnrot
  • 20,609
  • 17
  • 79
  • 141