Dears,
how to calculate work experience with TimeSpan or otherwise how to calculate work experience if all months of the year have 31 days?

Dani AI

Generated

Short answer: decide whether you want a total elapsed interval (days/hours) or a calendar-style result (years, months, days). is right that TimeSpan works for totals, but TimeSpan cannot express "months" or "years" correctly because months have different lengths. is also right to flag the idea of treating every month as 31 days — that produces wrong calendar math (and breaks with February/leap years).

If you need a calendar result like "3 years, 2 months, 5 days", compute it from two DateTime values and borrow days/months when needed. Example routine (C#) that returns years/months/days:

public static void GetYearsMonthsDays(DateTime start, DateTime end, out int years, out int months, out int days)
{
    if (end < start) { var tmp = start; start = end; end = tmp; }
    years = end.Year - start.Year;
    months = end.Month - start.Month;
    days = end.Day - start.Day;
    if (days < 0)
    {
        months--;
        var prev = end.AddMonths(-1);
        days += DateTime.DaysInMonth(prev.Year, prev.Month);
    }
    if (months < 0)
    {
        years--;
        months += 12;
    }
}

Notes and cautions: decide whether the end date is inclusive or exclusive (CV conventions vary). If calculating "work days" exclude weekends/holidays and use a business-day counter instead of calendar months. For time-zone and DST correctness (and clearer Period semantics) consider a dedicated library such as NodaTime. For core .NET behavior see DateTime documentation for component operations and subtraction.

References: DateTime documentation and NodaTime.

Recommended Answers

All 2 Replies

Your question is a little vague on details, but you could initialize a new TimeSpan:

TimeSpan span = new TimeSpan();

Then iterate through your list of hours and add them as a new TimeSpan:

span += new TimeSpan(hours, minutes, seconds);

I don't understand what to are trying to get at with "if all months of the year have 31 days?". Could you elaborate? Or post some code?

A calendar is a wonderfull thing. With months of 31 days we soon have New Yearsday in the middle of summer! 12*31 being 372.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.