Year, Month, Days, hours between two dates
我需要找出两个日期之间的区别并显示结果年、月、日和小时格式,例如1年、2个月、6天和4小时。
我该怎么做呢?每天和每小时都很简单。但是一年又一个月让我很难过。
我需要100%准确的结果…我们不能假设每月30天或每年356天。请帮忙,谢谢。
准确计算年数、月数和实际天数(因为
我将在这里创建一个名为
代码如下:
DATEDIFF类:
2您可以这样测试主代码:
测试代码:
1 2 3 4 5 |
查看日期时间:http://msdn.microsoft.com/en-us/library/system.datetime(v=vs.110).aspx
你可以做像
1 2 3 4 5 | var timeSpan = dateTime2 - dateTime1; var years = timeSpan.Days / 365; var months = (timeSpan.Days - years * 365)/30; var days = timeSpan.Days - years * 365 - months * 30; // and so on |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | class Program { static void Main() { DateTime oldDate = new DateTime(2014,1,1); DateTime newDate = DateTime.Now; TimeSpan dif = newDate - oldDate; int leapdays = GetLeapDays(oldDate, newDate); var years = (dif.Days-leapdays) / 365; int otherdays = GetAnOtherDays(oldDate, newDate , years); int months = (int)((dif.Days - (leapdays + otherdays)- (years * 365)) / 30); int days = (int)(dif.Days - years * 365 - months * 30) - (leapdays + otherdays); Console.WriteLine("Edad es {0} a?os, {1} meses, {2} días", years, months, days) ; Console.ReadLine(); } public static int GetAnOtherDays(DateTime oldDate, DateTime newDate, int years) { int days = 0; oldDate = oldDate.AddYears(years); DateTime oldDate1 = oldDate.AddMonths(1); while ((oldDate1.Month <= newDate.Month && oldDate1.Year<=newDate.Year) || (oldDate1.Month>newDate.Month && oldDate1.Year<newDate.Year)) { days += ((TimeSpan)(oldDate1 - oldDate)).Days - 30; oldDate = oldDate.AddMonths(1); oldDate1 = oldDate.AddMonths(1); } return days; } public static int GetLeapDays(DateTime oldDate, DateTime newDate) { int days = 0; while (oldDate.Year < newDate.Year) { if (DateTime.IsLeapYear(oldDate.Year)) days += 1; oldDate = oldDate.AddYears(1); } return days; } } |