S8PeriodHelper.cs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. namespace Admin.NET.Plugin.AiDOP.Infrastructure.S8;
  2. /// <summary>
  3. /// 首版按服务器自然周期对齐大屏统计口径;显式日期范围优先于 period。
  4. /// </summary>
  5. public static class S8PeriodHelper
  6. {
  7. /// <summary>
  8. /// 将 period 字符串解析为半开区间 [from, to)。
  9. /// 支持 today / this_week / this_month(大小写容错)。
  10. /// 非法或空值返回 (null, null),调用方保持全量行为。
  11. /// </summary>
  12. public static (DateTime? from, DateTime? to) Resolve(string? period)
  13. {
  14. if (string.IsNullOrWhiteSpace(period)) return (null, null);
  15. var today = DateTime.Today;
  16. return period.Trim().ToLowerInvariant() switch
  17. {
  18. "today" => (today, today.AddDays(1)),
  19. "this_week" => ResolveThisWeek(today),
  20. "this_month" => (new DateTime(today.Year, today.Month, 1), new DateTime(today.Year, today.Month, 1).AddMonths(1)),
  21. "last_24h" => (DateTime.Now.AddHours(-24), DateTime.Now),
  22. "last_7d" => (today.AddDays(-6), today.AddDays(1)),
  23. "last_30d" => (today.AddDays(-29), today.AddDays(1)),
  24. _ => (null, null),
  25. };
  26. }
  27. private static (DateTime? from, DateTime? to) ResolveThisWeek(DateTime today)
  28. {
  29. // 周一作为周起始(DayOfWeek.Monday = 1)
  30. var offset = ((int)today.DayOfWeek - (int)DayOfWeek.Monday + 7) % 7;
  31. var monday = today.AddDays(-offset);
  32. return (monday, monday.AddDays(7));
  33. }
  34. }