S8PeriodHelper.cs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  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 / this_quarter(大小写容错)。
  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. "this_quarter" => ResolveThisQuarter(today),
  22. "last_24h" => (DateTime.Now.AddHours(-24), DateTime.Now),
  23. "last_7d" => (today.AddDays(-6), today.AddDays(1)),
  24. "last_30d" => (today.AddDays(-29), today.AddDays(1)),
  25. _ => (null, null),
  26. };
  27. }
  28. private static (DateTime? from, DateTime? to) ResolveThisWeek(DateTime today)
  29. {
  30. // 周一作为周起始(DayOfWeek.Monday = 1)
  31. var offset = ((int)today.DayOfWeek - (int)DayOfWeek.Monday + 7) % 7;
  32. var monday = today.AddDays(-offset);
  33. return (monday, monday.AddDays(7));
  34. }
  35. private static (DateTime? from, DateTime? to) ResolveThisQuarter(DateTime today)
  36. {
  37. // 季度起始月:1 / 4 / 7 / 10
  38. var quarterStartMonth = ((today.Month - 1) / 3) * 3 + 1;
  39. var start = new DateTime(today.Year, quarterStartMonth, 1);
  40. return (start, start.AddMonths(3));
  41. }
  42. }