如何将天数转换为年,月和日

如果我有两个约会,那么我会在几天内得到它们之间的区别像这篇文章 。


如何在以下视图中详细说明:

将天number of years,number of months and the rest in the number of days转换为( number of years,number of months and the rest in the number of days

没有“开箱即用”的解决方案。 问题是你正在处理可变数据,即并非所有年份都是365天,在闰年它变为366.此外,不是每个月都可以假定为标准的30天。

在没有上下文的情况下计算此类信息非常困难 – 但是,您需要以天为单位来计算(至少准确地)您需要上下文的年/月数。 例如,您需要知道您正在处理的特定月份和特定年份,以确定该年份是否为闰年,或者该特定月份是否为30/31天等等……


根据您的意见和以下条件

  • 1年= 365天
  • 1个月= 30天

然后,以下代码将完成这项工作

 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); 

您不能因为它取决于开始日期,即30天可能是1个月1天,或1个月2天,或不到一个月或365天将少于一年,如果它是闰年

如前面的答案所述,很难在短短几天内解决这个问题。 闰年存在问题,以及以月为单位的天数。 如果从原始的两个日期时间开始,则可以使用类似于以下内容的代码:

 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)"); 

输出为: Difference: 3 year(s), 1 month(s), 4 day(s)