Date difference in years using C#
我如何计算年中两个日期之间的日期差?
例如:
我已经编写了一个实现,它可以正确地处理相隔一年的日期。
但是,与其他算法不同,它不能优雅地处理负时间跨度。它也不使用自己的日期算法,而是依赖于标准库。
因此,不用再多费吹灰之力,下面是代码:
1 2 3 4 5 6 7 8 9 10 11 12 | DateTime zeroTime = new DateTime(1, 1, 1); DateTime a = new DateTime(2007, 1, 1); DateTime b = new DateTime(2008, 1, 1); TimeSpan span = b - a; // Because we start at year 1 for the Gregorian // calendar, we must subtract a year here. int years = (zeroTime + span).Year - 1; // 1, where my other algorithm resulted in 0. Console.WriteLine("Yrs elapsed:" + years); |
用途:
1 2 3 4 5 6 | int Years(DateTime start, DateTime end) { return (end.Year - start.Year - 1) + (((end.Month > start.Month) || ((end.Month == start.Month) && (end.Day >= start.Day))) ? 1 : 0); } |
我们必须对支票进行编码,以确定两个日期之间的差异是否大于2年,即开始日期和结束日期。
由于上面的提示,完成如下:
1 2 3 4 5 | DateTime StartDate = Convert.ToDateTime("01/01/2012"); DateTime EndDate = Convert.ToDateTime("01/01/2014"); DateTime TwoYears = StartDate.AddYears(2); if EndDate > TwoYears ..... |
如果你需要它来了解某人的年龄是因为一些微不足道的原因,那么时间跨度是可以的,但是如果你需要计算退休金、长期存款或其他财务、科学或法律上的目的,那么时间跨度恐怕不够准确,因为时间跨度假定每年有相同的天数、相同的小时和相同的秒数)。
事实上,有些年份的长度会有所不同(因为不同的原因,这些原因不在这个答案的范围之内)。为了克服时间跨度的限制,您可以模拟Excel的功能,即:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | public int GetDifferenceInYears(DateTime startDate, DateTime endDate) { //Excel documentation says"COMPLETE calendar years in between dates" int years = endDate.Year - startDate.Year; if (startDate.Month == endDate.Month &&// if the start month and the end month are the same endDate.Day < startDate.Day// AND the end day is less than the start day || endDate.Month < startDate.Month)// OR if the end month is less than the start month { years--; } return years; } |
1 2 3 |
维基百科/闰年的平均天数。
目前还不清楚您希望如何处理分数年份,但可能是这样:
1 2 3 4 5 | DateTime now = DateTime.Now; DateTime origin = new DateTime(2007, 11, 3); int calendar_years = now.Year - origin.Year; int whole_years = calendar_years - ((now.AddYears(-calendar_years) >= origin)? 0: 1); int another_method = calendar_years - ((now.Month - origin.Month) * 32 >= origin.Day - now.Day)? 0: 1); |
我实现了一个扩展方法来获取两个日期之间的年数,用整个月份四舍五入。
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 | /// <summary> /// Gets the total number of years between two dates, rounded to whole months. /// Examples: /// 2011-12-14, 2012-12-15 returns 1. /// 2011-12-14, 2012-12-14 returns 1. /// 2011-12-14, 2012-12-13 returns 0,9167. /// </summary> /// <param name="start"> /// Stardate of time period /// </param> /// <param name="end"> /// Enddate of time period /// </param> /// <returns> /// Total Years between the two days /// </returns> public static double DifferenceTotalYears(this DateTime start, DateTime end) { // Get difference in total months. int months = ((end.Year - start.Year) * 12) + (end.Month - start.Month); // substract 1 month if end month is not completed if (end.Day < start.Day) { months--; } double totalyears = months / 12d; return totalyears; } |
这是一个让系统自动处理闰年的巧妙技巧。它给出了所有日期组合的准确答案。
1 2 3 4 5 6 7 8 9 10 11 12 |
如果你想让别人的年龄,看看这个
我如何用C来计算某人的年龄?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | public string GetAgeText(DateTime birthDate) { const double ApproxDaysPerMonth = 30.4375; const double ApproxDaysPerYear = 365.25; int iDays = (DateTime.Now - birthDate).Days; int iYear = (int)(iDays / ApproxDaysPerYear); iDays -= (int)(iYear * ApproxDaysPerYear); int iMonths = (int)(iDays / ApproxDaysPerMonth); iDays -= (int)(iMonths * ApproxDaysPerMonth); return string.Format("{0} ?r, {1} m?neder, {2} dage", iYear, iMonths, iDays); } |
1 |
我在时间跨度上发现这个,很多年,几个月,几天:
1 2 3 | DateTime target_dob = THE_DOB; DateTime true_age = DateTime.MinValue + ((TimeSpan)(DateTime.Now - target_dob )); // Minimum value as 1/1/1 int yr = true_age.Year - 1; |
下面是基于Dana的简单代码,它在大多数情况下都能产生正确的答案。但它没有考虑到两个日期之间不到一年的时间。下面是我用来产生一致结果的代码:
1 2 3 4 5 6 | public static int DateDiffYears(DateTime startDate, DateTime endDate) { var yr = endDate.Year - startDate.Year - 1 + (endDate.Month >= startDate.Month && endDate.Day >= startDate.Day ? 1 : 0); return yr < 0 ? 0 : yr; } |
1 2 3 4 5 6 7 | DateTime musteriDogum = new DateTime(dogumYil, dogumAy, dogumGun); int additionalDays = ((DateTime.Now.Year - dogumYil) / 4); //Count of the years with 366 days int extraDays = additionalDays + ((DateTime.Now.Year % 4 == 0 || musteriDogum.Year % 4 == 0) ? 1 : 0); //We add 1 if this year or year inserted has 366 days int yearsOld = ((DateTime.Now - musteriDogum).Days - extraDays ) / 365; // Now we extract these extra days from total days and we can divide to 365 |
如果你处理的是月份和年份,你需要知道每个月有多少天,哪些年份是闰年。
输入公历(和其他特定于文化的日历实现)。
虽然日历不提供直接计算两个时间点之间差异的方法,但它确实有一些方法,例如
1 2 3 | DateTime AddWeeks(DateTime time, int weeks) DateTime AddMonths(DateTime time, int months) DateTime AddYears(DateTime time, int years) |
简单解决方案:
1 2 3 4 5 6 7 8 9 10 | public int getYearDiff(DateTime startDate, DateTime endDate){ int y = Year(endDate) - Year(startDate); int startMonth = Month(startDate); int endMonth = Month(endDate); if (endMonth < startMonth) return y - 1; if (endMonth > startMonth) return y; return (Day(endDate) < Day(startDate) ? y - 1 : y); } |
也许这有助于回答以下问题:给定年份的天数,
1 |
关于datetime.dayOfYear属性。
这是计算年和月差异的最佳代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | DateTime firstDate = DateTime.Parse("1/31/2019"); DateTime secondDate = DateTime.Parse("2/1/2016"); int totalYears = firstDate.Year - secondDate.Year; int totalMonths = 0; if (firstDate.Month > secondDate.Month) totalMonths = firstDate.Month - secondDate.Month; else if (firstDate.Month < secondDate.Month) { totalYears -= 1; int monthDifference = secondDate.Month - firstDate.Month; totalMonths = 12 - monthDifference; } if ((firstDate.Day - secondDate.Day) == 30) { totalMonths += 1; if (totalMonths % 12 == 0) { totalYears += 1; totalMonths = 0; } } |
作品完美:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | internal static int GetDifferenceInYears(DateTime startDate) { int finalResult = 0; const int DaysInYear = 365; DateTime endDate = DateTime.Now; TimeSpan timeSpan = endDate - startDate; if (timeSpan.TotalDays > 365) { finalResult = (int)Math.Round((timeSpan.TotalDays / DaysInYear), MidpointRounding.ToEven); } return finalResult; } |
希望下面的链接有帮助
msdn-datetime.subtract.method(日期时间)
甚至还有一些关于C的例子。只需单击"C语言"选项卡。
祝你好运