2010-11-08 13 views
52

如何计算年份中两个日期之间的日期差异?例如:(Datetime.Now.Today() - 11/03/2007)年。使用C#年的日期差异使用C#

+0

信用点击欺骗去杜格特。 – 2010-11-08 20:52:06

+1

您标记为答案的代码实际上并不正确。它可能会返回不正确的结果 – Mick 2015-06-29 07:47:58

+0

我很惊讶以下有多少答案是不正确的,但投票。 – Mick 2015-06-29 07:58:22

回答

78

我已经写了一个实现,正确使用相隔一年的日期。

但是,它不会优雅地处理负时间片,不像其他算法。它也不使用自己的日期算法,而是依赖于标准库。

因此,事不宜迟,这里是代码:

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

平均处理闰年,但每年最多可达18小时。 – 2010-11-08 19:48:42

+5

使用此方法,1/1/2007和1/1/2008之间的差异将为0年。直观地说,它应该是1年。 – 2010-11-08 21:16:33

+2

好点。我不知道有任何其他有效的方法,尽管...可能会添加一个到今天? – 2010-11-08 23:09:16

4

目前还不清楚要如何处理小数年,但也许是这样的:从Wikipedia/Leap_year

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

根据这种方法,2/28/2009是2008年2月29日以后的1年,而它似乎应该略低于1年。我想闰年的处理总是会有些不尽人意。 – 2010-11-08 21:44:42

+0

@o。 nate:修正,也许(使用Doggett发现的另一个问题上的一个技巧)。我认为像Dana的解决方案可能有必要在两个方向上解决闰日问题。 – 2010-11-08 21:59:33

5
var totalYears = 
    (DateTime.Today - new DateTime(2007, 03, 11)).TotalDays 
    /365.2425; 

的平均天数。

+0

一般正确。但不总是。 – Mick 2015-06-29 07:51:37

34

用途:

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); 
} 
+0

这就是说,2008年11月 - 02年是2007年 - 03年11月之后的一年,大多数人会说这是短短的一天。 – 2010-11-08 20:00:07

+0

你说得对。我更新了我的代码,严格禁用Year,Month和Day属性。现在它变得有点丑陋,但适用于闰年。 – dana 2010-11-08 20:13:51

+2

对于我的情况,这是解决方案 – 2015-06-30 15:07:49

0

如果你正在处理的几个月和几年,你需要的东西,知道每个月有多少天有和年是闰年。

输入Gregorian Calendar(和其他文化特定的Calendar实现)。

虽然日历不提供方法来直接计算两个时间点之间的差异,它确实有方法,如

DateTime AddWeeks(DateTime time, int weeks) 
DateTime AddMonths(DateTime time, int months) 
DateTime AddYears(DateTime time, int years) 
3

我实现了一个扩展方法来获得两个日期之间的年数,整整四个月。

/// <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; 
    } 
+0

该解决方案将每个月视为一年的1/12。它会歪斜,因为有些月份不是这样大小的 – 2014-06-12 05:30:29

+0

并不总是返回正确的结果 – Mick 2015-06-29 07:56:05

18

我们必须编码检查以确定两个日期之间的差异,开始日期和结束日期是否大于2年。

由于上述提示有人做过如下:

DateTime StartDate = Convert.ToDateTime("01/01/2012"); 
DateTime EndDate = Convert.ToDateTime("01/01/2014"); 
DateTime TwoYears = StartDate.AddYears(2); 

if EndDate > TwoYears ..... 
+1

也许不是一个实际的解决方案的问题,但它解决了我的问题,所以upvote :) – 2014-09-29 14:23:55

+3

较短的版本:If(Birthday.AddYears(18 )> DateTime.UtcNow.Date)// 18岁以下 – 2016-02-16 20:33:20

1

,我发现这个在TimeSpan for years, months and days

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; 
0
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
int Age = new DateTime((DateTime.Now - BirthDateTime).Ticks).Year; 
+0

因为四舍五入,实际上并不正确。我40岁了,那是报告41.我再3周没有41岁。 – 2015-06-04 07:15:25

+0

加上它没有正确记录闰年 – Mick 2015-06-29 07:52:48

2

这是一个巧妙的方法,它可以让系统自动处理闰年。它给出了所有日期组合的准确答案。

DateTime dt1 = new DateTime(1987, 9, 23, 13, 12, 12, 0); 
DateTime dt2 = new DateTime(2007, 6, 15, 16, 25, 46, 0); 

DateTime tmp = dt1; 
int years = -1; 
while (tmp < dt2) 
{ 
    years++; 
    tmp = tmp.AddYears(1); 
} 

Console.WriteLine("{0}", years); 
+1

简单而有效! – 2016-05-04 07:49:27

8

如果你需要它知道一个人的年龄为微不足道的原因,然后入库时间是确定的,但如果你需要计算养老金,长期存款或任何其他为金融,科学或法律目的的话,只怕时间跨度赢得这是不够准确的,因为Timespan假设每年有相同的天数,相同的小时数和相同的秒数)。

实际上,某些年份的长度会有所不同(因为不同的原因超出了本答案的范围)。为了解决时间跨度的限制,那么你可以模仿什么的Excel做是:

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; 
    } 
0
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 
0

简单的解决方案:

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

也许这将是回答这个问题有所帮助:在天计数某一年

new DateTime(anyDate.Year, 12, 31).DayOfYear //will include leap years too 

关于DateTime.DayOfYear Property

0

这是计算年份和月份差最好代码:

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; 
    } 
} 
0

运行完美:

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; 
    } 
0

是基于关闭Dana的简单的代码产生在大多数情况下,正确的答案如下。但是它没有考虑到在日期之间不到一年的时间。所以这里是我用来产生一致的结果的代码:

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