47 lines
1.6 KiB
C#
47 lines
1.6 KiB
C#
using System;
|
|
using System.Linq;
|
|
using GazpromApp.Enums;
|
|
using GazpromApp.Models;
|
|
using GazpromApp.ViewModels;
|
|
|
|
namespace GazpromApp.Utils;
|
|
|
|
public static class DateCalculator
|
|
{
|
|
public static DateTime[] GetNearestDates(this InspectionViewModel inspection)
|
|
{
|
|
var today = DateTime.Today;
|
|
|
|
var firstFutureDate = AddPeriod(inspection.InspectionDate.DateTime, inspection.PeriodType, inspection.PeriodValue);
|
|
|
|
if (firstFutureDate > today)
|
|
{
|
|
return [inspection.InspectionDate.DateTime, firstFutureDate];
|
|
}
|
|
|
|
DateTime futureDate = Enumerable.Range(1, int.MaxValue)
|
|
.Select(i => AddPeriod(inspection.InspectionDate.DateTime, inspection.PeriodType, inspection.PeriodValue * i))
|
|
.First(d => d > today);
|
|
|
|
DateTime pastDate = SubtractPeriod(futureDate, inspection.PeriodType, inspection.PeriodValue);
|
|
|
|
return [pastDate, futureDate];
|
|
}
|
|
|
|
private static DateTime AddPeriod(DateTime date, PeriodType periodType, float value)
|
|
{
|
|
return periodType switch
|
|
{
|
|
PeriodType.Day => date.AddDays(value),
|
|
PeriodType.Week => date.AddDays(value * 7),
|
|
PeriodType.Month => date.AddDays(value * 30.436875), // Avg days/month
|
|
PeriodType.Year => date.AddDays(value * 365.2425), // Avg days/year (incl. leap years)
|
|
_ => throw new ArgumentException("Invalid period type")
|
|
};
|
|
}
|
|
|
|
private static DateTime SubtractPeriod(DateTime date, PeriodType periodType, float value)
|
|
{
|
|
return AddPeriod(date, periodType, -value);
|
|
}
|
|
} |