Forum Discussion
Kristin_Lyons
May 29, 2024Copper Contributor
Calculating Length of Service from days to Years/Months/Days
I am trying to calculate employees Length of Service from Total days to Years/Months/Days. What formula(s) would I use for that type of calculation? 05/27/24 Length of Service Start Date ...
mfcorral
Copper Contributor
Kristin_Lyons depending on what are your accuracy requirements. Your need to choose between two calculations:
- Treat every month as a 30 days month, ignoring your Start Date field and leap years (every year will be 365 days long). This approach simpliflies the calculations but is not exact.
- Start to count from your Start Date field, filling every month and taking into account leap years in order to correctly fill February. This approach is a little more complex.
Regardless of your choice, you don't need the first decimal Years field.
Hope this helps,
Miguel.
Kristin_Lyons
May 31, 2024Copper Contributor
mfcorral accuracy is what I need. Can you give me an example formula? I am thinking thatvwill become a long formula, like the 12 year calculation. Trying to understand what the formula would look like.
Kristin
- mfcorralJun 01, 2024Copper Contributor
Hi again Kristin_Lyons, more than a formula you need and algorithm. In C#:
using System; public class Program { public static void Main() { var startDate = new DateTime(2012, 5, 21); var totalDays = 2102; var span = GetDateTimeSpan(startDate, totalDays); Console.WriteLine($"Years: {span.Years}"); Console.WriteLine($"Months: {span.Months}"); Console.WriteLine($"Days: {span.Days}"); } public static (int Years, int Months, int Days) GetDateTimeSpan(DateTime startDate, int totalDays) { int years = 0; int months = 0; int days = 0; var endDate = startDate.AddDays(totalDays); var currentDate = endDate; // If totalDays is negative, swap dates if (startDate > endDate) { endDate = startDate; startDate = currentDate; } // Count years currentDate = startDate; while (currentDate.AddYears(years + 1) <= endDate) { years++; } // Count months currentDate = currentDate.AddYears(years); while (currentDate.AddMonths(months + 1) <= endDate) { months++; } // Count days currentDate = currentDate.AddMonths(months); while (currentDate.AddDays(days + 1) <= endDate) { days++; } return (years, months, days); } }
You can play with it at https://dotnetfiddle.net/. Be sure that you choose the following options:
- Language: C#
- Project type: Console
- Compiler: .NET 8
Replace all the code, and you got it.
Regards,
Miguel.