我有两个日期: 2011-07-05
和 2013-10-05
如何获得格式的持续时间: 2 years 3 months
。什么是最好的方法?
我可以为此创建任何扩展方法或新类吗?请指教?任何帮助将不胜感激
到目前为止我已经完成了:
public static string GetDuration(DateTime date1, DateTime date2) {
int oldMonth = date2.Month;
while (oldMonth == date2.Month) {
date1 = date1.AddDays(-1);
date2 = date2.AddDays(-1);
}
int years = 0, months = 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) {
date2 = date2.AddDays(-1);
if ((date2.CompareTo(date1) >= 0) && (oldMonth != date2.Month)) {
months++;
oldMonth = date2.Month;
}
}
return
"Difference: " +
years.ToString() + " years" +
", " + months.ToString() + " months";
}
答案 0 :(得分:1)
public static string GetDuration(DateTime date1, DateTime date2)
{
TimeSpan difference = date2 - date1;
DateTime result = DateTime.MinValue.AddDays(difference.TotalDays);
int years = result.Year - 1;
int months = result.Month - 1;
int days = result.Day - 1;
return $"{years} years {months} months";
}
答案 1 :(得分:0)
public static string GetDuration(DateTime date1, DateTime date2)
{
var period = date2.AddDays(1) - date1;
var date = new DateTime(period.Ticks);
var totalYears = date.Year - 1;
var totalMonths = ((date.Year - 1) * 12) + date.Month - 1;
var extraMonths = totalMonths - (totalYears * 12);
return string.Format("{0} years {1} months", totalYears, extraMonths);
}
您可以查看实际操作here。
答案 2 :(得分:0)
没有考虑实际日期,这是一个快速的解决方案
int year, month;
if(date2.Month >= date1.Month)
{
years = date2.Year - date1.Year;
months = date2.Month - date1.Month;
}
else
{
years = date2.Year - date1.Year - 1;
months= date2.Month + 12 - date1.Month;
}