2

I have the following code:

 var datesMove = (newState.Milestone- oldState.Milestone).TotalDays;

that shows me the number of days between two dates.

This works fine but i am displaying this on a webpage and instead of showing

Date Move: 43 days:

My Users have asked to see something like: 1 month 3 days or 1 year, 3 months and 2 days.

Is there any helper function built in that takes the difference in dates and displaying it in the highest level of aggregation possible like my examples above?

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
leora
  • 188,729
  • 360
  • 878
  • 1,366
  • Related: http://stackoverflow.com/q/1525990/497356. Basically `TimeSpan` doesn't have a concept of "months" or "years" because those require some context as to the time period the difference is taken – Andrew Whitaker Sep 28 '14 at 13:54
  • There's no built in function for this. – artm Sep 28 '14 at 13:55

2 Answers2

2

http://humanizr.net/ is a nice third-party tool for this:

FromDays(1).Humanize(precision:2) => "1 day" // no difference when there is only one unit in the provided TimeSpan
TimeSpan.FromDays(16).Humanize(2) => "2 weeks, 2 days"

// the same TimeSpan value with different precision returns different results
TimeSpan.FromMilliseconds(1299630020).Humanize() => "2 weeks"
TimeSpan.FromMilliseconds(1299630020).Humanize(3) => "2 weeks, 1 day, 1 hour"
TimeSpan.FromMilliseconds(1299630020).Humanize(4) => "2 weeks, 1 day, 1 hour, 30 seconds"
TimeSpan.FromMilliseconds(1299630020).Humanize(5) => "2 weeks, 1 day, 1 hour, 30 seconds, 20 milliseconds"

ref: http://www.hanselman.com/blog/NuGetPackageOfTheWeekHumanizerMakesNETDataTypesMoreHuman.aspx

Keith Payne
  • 3,002
  • 16
  • 30
-1

You can try this code:

DateTime StartDate = Convert.ToDateTime("01/1/2010"); 
DateTime EndDate = Convert.ToDateTime("04/3/2011");
string strResult = CalculateDays(StartDate, EndDate);

public string CalculateDays(DateTime StartDate, DateTime EndDate)
{
DateTime oldDate;

DateTime.TryParse(StartDate.ToShortDateString(), out oldDate);
DateTime currentDate = EndDate;

TimeSpan difference = currentDate.Subtract(oldDate);

// This is to convert the timespan to datetime object
DateTime DateTimeDifferene = DateTime.MinValue + difference;

// Min value is 01/01/0001
// subtract our addition or 1 on all components to get the 
//actual date.

int InYears = DateTimeDifferene.Year - 1;
int InMonths = DateTimeDifferene.Month - 1;
int InDays = DateTimeDifferene.Day - 1;


return InYears.ToString() +" Years "+ InMonths.ToString() +" Months " + InDays.ToString() +" Days";
}

found here: http://forums.asp.net/t/1645050.aspx?Convert+number+of+days+to+days+months+years

kleinohad
  • 5,800
  • 2
  • 26
  • 34