If i have Two dates then i get the difference between them in days Like this Post.
How to detail that in the following view :
convert the days to (number of years,number of months and the rest in the number of days
)
If i have Two dates then i get the difference between them in days Like this Post.
How to detail that in the following view :
convert the days to (number of years,number of months and the rest in the number of days
)
There is no out-of-the-box solution for this. The problem is the data isn't "fixed" e.g. not all years are 365 days (366 on a leap year) and not every month can be assumed to be standard 30 days.
It's very difficult to calculate this sort of information without context. You have a duration in days, however, to accurately calculate the number of years/months you need to know exactly when these days fall i.e. on what month and of what year - this would allow you to determine the exact days in the month and/or year.
Based on your comments and the following conditions
Then the following code would do the job
DateTime startDate = new DateTime(2010, 1, 1);
DateTime endDate = new DateTime(2013, 1, 10);
var totalDays = (endDate - startDate).TotalDays;
var totalYears = Math.Truncate(totalDays / 365);
var totalMonths = Math.Truncate((totalDays % 365) / 30);
var remainingDays = Math.Truncate((totalDays % 365) % 30);
Console.WriteLine("Estimated duration is {0} year(s), {1} month(s) and {2} day(s)", totalYears, totalMonths, remainingDays);
You can't because it depends on the start date i.e. 30 days may be 1 month 1 day, or 1 month 2 days, or less than a month or 365 days will be less than a year if it's a leap year
As mentioned in previous answers, it is very difficult to work this out from just a number of days. There is problems with leap years, and the number of days in months. If you start with the original two datetimes you can use code similar to the following:
DateTime date1 = new DateTime(2010, 1, 18);
DateTime date2 = new DateTime(2013, 2, 22);
int oldMonth = date2.Month;
while (oldMonth == date2.Month)
{
date1 = date1.AddDays(-1);
date2 = date2.AddDays(-1);
}
int years = 0, months = 0, days = 0, hours = 0, minutes = 0, seconds = 0, milliseconds = 0;
// getting number of years
while (date2.CompareTo(date1) >= 0)
{
years++;
date2 = date2.AddYears(-1);
}
date2 = date2.AddYears(1);
years--;
// getting number of months and days
oldMonth = date2.Month;
while (date2.CompareTo(date1) >= 0)
{
days++;
date2 = date2.AddDays(-1);
if ((date2.CompareTo(date1) >= 0) && (oldMonth != date2.Month))
{
months++;
days = 0;
oldMonth = date2.Month;
}
}
date2 = date2.AddDays(1);
days--;
TimeSpan difference = date2.Subtract(date1);
Console.WriteLine("Difference: " +
years.ToString() + " year(s)" +
", " + months.ToString() + " month(s)" +
", " + days.ToString() + " day(s)");
Output is:Difference: 3 year(s), 1 month(s), 4 day(s)