98

2つの日付の日付の差を年単位で計算するにはどうすればよいですか?

例:(Datetime.Now.Today() - 11/03/2007)数年で。

4

19 に答える 19

136

正確に1年離れた日付で適切に機能する実装を作成しました。

ただし、他のアルゴリズムとは異なり、負のタイムスパンを適切に処理しません。また、独自の日付演算を使用せず、代わりに標準ライブラリに依存しています。

ですから、これ以上苦労することなく、ここにコードがあります:

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);
于 2010-11-08T19:45:54.963 に答える
59

使用する:

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);
}
于 2010-11-08T19:54:38.077 に答える
28

開始日と終了日の2つの日付の差が2年を超えているかどうかを確認するために、チェックをコーディングする必要がありました。

上記のヒントのおかげで、次のようになりました。

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

 if EndDate > TwoYears .....
于 2012-02-29T11:46:22.300 に答える
20

些細な理由で誰かの年齢を知るためにそれが必要な場合、タイムスパンは問題ありませんが、老齢年金、長期預金、またはその他の財政的、科学的、または法的な目的で計算する必要がある場合、タイムスパンは十分に正確ではないのではないかと思います毎年同じ日数、同じ時間数、同じ秒数があると想定しています)。

実際には、数年の長さは異なります(この回答の範囲外のさまざまな理由により)。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;
    }
于 2015-02-11T00:10:50.313 に答える
11
var totalYears = 
    (DateTime.Today - new DateTime(2007, 03, 11)).TotalDays
    / 365.2425;

ウィキペディア/うるう年からの平均日数。

于 2010-11-08T19:47:25.553 に答える
7
int Age = new DateTime((DateTime.Now - BirthDateTime).Ticks).Year;

経過年数(年齢)を計算すると、結果はマイナス1になります。

var timeSpan = DateTime.Now - birthDateTime;
int age = new DateTime(timeSpan.Ticks).Year - 1;
于 2014-02-04T13:20:00.653 に答える
6

これは、システムがうるう年を自動的に処理できるようにする巧妙なトリックです。すべての日付の組み合わせに対して正確な答えが得られます。

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);
于 2014-07-29T03:00:59.097 に答える
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);
于 2010-11-08T19:46:49.610 に答える
3

2つの日付の間の年数を月単位で四捨五入して取得する拡張メソッドを実装しました。

    /// <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;
    }
于 2012-01-03T11:58:22.427 に答える
2
    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);
    }
于 2014-01-21T13:58:01.323 に答える
1

私はこれをTimeSpanで何年も、何ヶ月も、何日も見つけました:

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;
于 2012-09-10T14:15:06.527 に答える
0

月と年を扱っている場合は、毎月何日あり、どの年がうるう年かを知っているものが必要です。

グレゴリオ暦(およびその他の文化固有のカレンダーの実装)を入力します。

カレンダーには、2つの時点の差を直接計算する方法はありませんが、次のような方法があります。

DateTime AddWeeks(DateTime time, int weeks)
DateTime AddMonths(DateTime time, int months)
DateTime AddYears(DateTime time, int years)
于 2011-06-04T08:28:48.470 に答える
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
于 2015-04-20T17:01:11.100 に答える
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);
}
于 2015-11-15T20:57:58.157 に答える
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;
    }
}
于 2016-04-20T14:01:14.997 に答える
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;
    }
于 2016-05-09T09:32:12.087 に答える
-1

多分これは質問に答えるのに役立つでしょう:与えられた年の日数

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

DateTime.DayOfYearプロパティについて。

于 2016-01-14T18:57:29.473 に答える
-1

以下は、ほとんどの場合に正しい答えを生成するDanaの単純なコードに基づいています。しかし、それは日付間の1年未満を考慮に入れていませんでした。したがって、一貫した結果を生成するために使用するコードは次のとおりです。

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;
}
于 2016-05-16T12:58:45.497 に答える
-2

以下のリンクがお役に立てば幸いです

MSDN-DateTime.Subtract.Method(DateTime)

そこにはC#の例もあります。[C#言語]タブをクリックするだけです。

幸運を

于 2010-11-08T22:43:49.930 に答える