EchoTex_Payroll/HRM.BO/Basic/DateDifferenceInYearsMonthDays.cs

137 lines
3.6 KiB
C#
Raw Normal View History

2024-10-14 10:01:49 +06:00
using System;
namespace HRM.BO
{
public struct DateDifferenceInYearsMonthDays
{
private readonly int years;
private readonly int months;
private readonly int days;
private readonly int hours;
private readonly int minutes;
private readonly int seconds;
private readonly int milliseconds;
public DateDifferenceInYearsMonthDays(int years, int months, int days, int hours, int minutes, int seconds,
int milliseconds)
{
this.years = years;
this.months = months;
this.days = days;
this.hours = hours;
this.minutes = minutes;
this.seconds = seconds;
this.milliseconds = milliseconds;
}
public int Years
{
get { return years; }
}
public int Months
{
get { return months; }
}
public int Days
{
get { return days; }
}
public int Hours
{
get { return hours; }
}
public int Minutes
{
get { return minutes; }
}
public int Seconds
{
get { return seconds; }
}
public int Milliseconds
{
get { return milliseconds; }
}
enum Phase
{
Years,
Months,
Days,
Done
}
public static DateDifferenceInYearsMonthDays CompareDates(DateTime date1, DateTime date2)
{
if (date2 < date1)
{
DateTime sub = date1;
date1 = date2;
date2 = sub;
}
DateTime current = date2;
int years = 0;
int months = 0;
int days = 0;
Phase phase = Phase.Years;
DateDifferenceInYearsMonthDays span = new DateDifferenceInYearsMonthDays();
while (phase != Phase.Done)
{
switch (phase)
{
case Phase.Years:
if (current.Year == 1 || current.AddYears(-1) < date1)
{
phase = Phase.Months;
}
else
{
current = current.AddYears(-1);
years++;
}
break;
case Phase.Months:
if (current.AddMonths(-1) < date1)
{
phase = Phase.Days;
}
else
{
current = current.AddMonths(-1);
months++;
}
break;
case Phase.Days:
if (current.AddDays(-1) < date1)
{
days++;
TimeSpan timespan = current - date1;
span = new DateDifferenceInYearsMonthDays(years, months, days, timespan.Hours,
timespan.Minutes, timespan.Seconds, timespan.Milliseconds);
phase = Phase.Done;
}
else
{
current = current.AddDays(-1);
days++;
}
break;
}
}
return span;
}
}
}