refactor: reorganize Infrastructure layer into folder structure with DI
This commit is contained in:
51
src/GreenHome.Infrastructure/Extensions/PersianDateHelper.cs
Normal file
51
src/GreenHome.Infrastructure/Extensions/PersianDateHelper.cs
Normal file
@@ -0,0 +1,51 @@
|
||||
using System.Globalization;
|
||||
|
||||
namespace GreenHome.Infrastructure.Extensions;
|
||||
|
||||
/// <summary>
|
||||
/// Helper methods for Persian (Solar Hijri) date calculations.
|
||||
/// Eliminates duplicate PersianCalendar code across services.
|
||||
/// </summary>
|
||||
public static class PersianDateHelper
|
||||
{
|
||||
private static readonly PersianCalendar PersianCalendar = new();
|
||||
|
||||
/// <summary>
|
||||
/// Extracts Persian year, month, day from a DateTime and returns the formatted Persian date string (yyyy/MM/dd).
|
||||
/// </summary>
|
||||
public static (int Year, int Month, int Day, string PersianDate) ToPersianDate(this DateTime dateTime)
|
||||
{
|
||||
var localDt = dateTime.Kind == DateTimeKind.Utc ? dateTime.ToLocalTime() : dateTime;
|
||||
var year = PersianCalendar.GetYear(localDt);
|
||||
var month = PersianCalendar.GetMonth(localDt);
|
||||
var day = PersianCalendar.GetDayOfMonth(localDt);
|
||||
var persianDate = $"{year:0000}/{month:00}/{day:00}";
|
||||
return (year, month, day, persianDate);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Validates a Persian date string in yyyy/MM/dd format and extracts year, month, day.
|
||||
/// </summary>
|
||||
public static bool TryParsePersianDate(string? persianDate, out int year, out int month, out int day)
|
||||
{
|
||||
year = month = day = 0;
|
||||
|
||||
if (string.IsNullOrWhiteSpace(persianDate))
|
||||
return false;
|
||||
|
||||
var parts = persianDate.Split('/');
|
||||
if (parts.Length != 3)
|
||||
return false;
|
||||
|
||||
if (!int.TryParse(parts[0], out year) || year < 1300 || year > 1500)
|
||||
return false;
|
||||
|
||||
if (!int.TryParse(parts[1], out month) || month < 1 || month > 12)
|
||||
return false;
|
||||
|
||||
if (!int.TryParse(parts[2], out day) || day < 1 || day > 31)
|
||||
return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user