diff --git a/XCode/Shards/TimeShardPolicy.cs b/XCode/Shards/TimeShardPolicy.cs
index c7dcc661e..a01979f31 100644
--- a/XCode/Shards/TimeShardPolicy.cs
+++ b/XCode/Shards/TimeShardPolicy.cs
@@ -1,5 +1,6 @@
using NewLife;
using XCode.Configuration;
+using XCode.Statistics;
namespace XCode.Shards;
@@ -22,6 +23,9 @@ public class TimeShardPolicy : IShardPolicy
/// 时间区间步进。遇到时间区间需要扫描多张表时的时间步进,默认1天
public TimeSpan Step { get; set; } = TimeSpan.FromDays(1);
+ /// 日期级别。年月日
+ public StatLevels Level { get; set; }
+
private readonly String? _fieldName;
#endregion
@@ -227,14 +231,29 @@ private ShardModel[] GetModels(DateTime start, DateTime end)
{
var models = new List();
+ // 猜测时间步进级别
+ var st = Step;
+ var level = Level;
+ if (level <= 0)
+ {
+ if (st.TotalDays >= 360)
+ level = StatLevels.Year;
+ else if (st.TotalDays >= 28 && st.TotalDays <= 31)
+ level = StatLevels.Month;
+ else if (st.TotalDays == 1)
+ level = StatLevels.Day;
+ else if (st.TotalHours == 1)
+ level = StatLevels.Hour;
+ }
+
// 根据不仅,把start调整到整点
- if (Step.TotalDays >= 1)
+ if (st.TotalDays >= 1)
start = start.Date;
else if (start.Hour >= 1)
start = start.Date.AddHours(start.Hour);
var hash = new HashSet();
- for (var dt = start; dt < end; dt = dt.Add(Step))
+ for (var dt = start; dt < end;)
{
var model = Shard(dt);
if (model != null)
@@ -246,6 +265,18 @@ private ShardModel[] GetModels(DateTime start, DateTime end)
hash.Add(key);
}
}
+
+ // 根据时间步进级别调整时间,解决每月每年时间不固定的问题
+ if (level == StatLevels.Year)
+ dt = dt.AddYears(1);
+ else if (level == StatLevels.Month)
+ dt = dt.AddMonths(1);
+ else if (level == StatLevels.Day)
+ dt = dt.AddDays(1);
+ else if (level == StatLevels.Hour)
+ dt = dt.AddHours(1);
+ else
+ dt = dt.Add(st);
}
//// 标准时间区间 start <= @fi < end ,但是要考虑到end有一部分落入新的分片,减一秒判断