Domanda

    

Questa domanda ha già una risposta qui:

         

Come posso calcolare la data differenza tra due date in anni?

Ad esempio:. (Datetime.Now.Today() - 11/03/2007) negli anni

È stato utile?

Soluzione

ho scritto un'implementazione che funzioni correttamente con date esattamente un anno di distanza.

Tuttavia, non gestisce con garbo timespans negativi, a differenza degli altri algoritmo. Inoltre non utilizzare il proprio data l'aritmetica, anziché far valere la libreria standard per questo.

Quindi, senza ulteriori indugi, ecco il codice:

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

Altri suggerimenti

Usa:

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

Abbiamo avuto in codice un controllo per stabilire se la differenza tra due date, una data di inizio e fine era superiore a 2 anni.

Grazie ai suggerimenti di cui sopra è stato fatto nel modo seguente:

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

 if EndDate > TwoYears .....

Se avete bisogno di conoscere l'età di una persona per futili motivi poi Timespan è OK ma se avete bisogno per il calcolo dei fondi pensione, i depositi a lungo termine o qualsiasi altra cosa per scopi finanziari, scientifici o giuridiche allora ho paura Timespan non sarà precisa basta perché Timespan presuppone che ogni anno ha lo stesso numero di giorni, lo stesso # di ore e lo stesso # di secondi).

In realtà la lunghezza di alcuni anni varierà (per motivi diversi che si trovano al di fuori del campo di applicazione di questa risposta). Per aggirare la limitazione di Timespan allora si può imitare ciò che Excel fa che è:

    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;
    }
var totalYears = 
    (DateTime.Today - new DateTime(2007, 03, 11)).TotalDays
    / 365.2425;

I giorni medi di Wikipedia / Leap_year .

E 'chiaro come si desidera gestire anni frazionali, ma forse in questo modo:

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

I implementato un metodo di estensione per ottenere il numero di anni tra due date, arrotondato per mesi interi.

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

Ecco un trucco che permette l'accordo di sistema con gli anni bisestili automagicamente. Dà una risposta precisa per tutte le combinazioni di data.

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

Se si sta cercando di ottenere l'età di qualcuno vedere questo

Come faccio a calcolare l'età di una persona in C #?

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

Ho trovato questo a TimeSpan per anni, mesi e giorni :

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;

Se hai a che fare con i mesi e gli anni avete bisogno di qualcosa che sa quanti giorni ogni mese ha e quali anni sono gli anni bisestili.

Inserisci il Gregoriano Calendario (e altra cultura SPECIFICI Calendario implementazioni).

Mentre Calendario non fornisce metodi per calcolare direttamente la differenza tra i due punti nel tempo, ha i metodi come

DateTime AddWeeks(DateTime time, int weeks)
DateTime AddMonths(DateTime time, int months)
DateTime AddYears(DateTime time, int years)
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

Opere perfetto:

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

Soluzione semplice:

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

Forse questo sarà utile per rispondere alla domanda: Conte di giorni determinato anno ,

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

Per quanto riguarda la DateTime.DayOfYear proprietà .

Questo è il miglior codice per calcolare l'anno e il mese differenza:

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

Di seguito è basato fuori semplice codice di Dana, che produce la risposta corretta nella maggior parte dei casi. Ma non ha preso in considerazione a meno di un anno tra le date. Così qui è il codice che uso per produrre risultati coerenti:

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

Spero che il link qui sotto aiuta

MSDN - DateTime.Subtract.Method (DateTime)

Non c'è esempi anche per C # là. Basta semplicemente fare clic sulla scheda linguaggio C #.

In bocca al lupo

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top