aki*_*kif 27 c# comparison datetime
我正在进行DateTime比较,但我不想在秒,毫秒和刻度级别进行比较.什么是最优雅的方式?
如果我只是比较DateTime,那么由于滴答差异,它们很少相等.
Jam*_*ass 30
那么使用时间跨度呢?
if (Math.Truncate((A - B).TotalMinutes) == 0)
{
//There is less than one minute between them
}
Run Code Online (Sandbox Code Playgroud)
可能不是最优雅的方式,但它允许相隔一秒但仍然具有不同的日/小时/分钟部分的情况,例如过夜.
编辑:我发现截断是不必要的......
if (Math.Abs((A - B).TotalMinutes) < 1)
{
//There is less than one minute between them
}
Run Code Online (Sandbox Code Playgroud)
我个人认为这更优雅......
一种方法可能是从您想要比较的值创建两个新的DateTime,但忽略从秒开始的任何内容,然后比较这些:
DateTime compare1 = new DateTime(year1, month1, day1, hour1, minute1, 0);
DateTime compare2 = new DateTime(year2, month2, day2, hour2, minute2, 0);
int result = DateTime.Compare(compare1, compare2);
Run Code Online (Sandbox Code Playgroud)
我是第一个承认它不优雅的人,但它解决了这个问题.
使用TimeSpan,您可以获得所需的所有粒度:
DateTime dt1, dt2;
double d = (dt2 - dt1).TotalDays;
double h = (dt2 - dt1).TotalHours;
double m = (dt2 - dt1).TotalMinutes;
double s = (dt2 - dt1).TotalSeconds;
double ms = (dt2 - dt1).TotalMilliseconds;
double ticks = (dt2 - dt1).Ticks;
Run Code Online (Sandbox Code Playgroud)
小智 5
public class DateTimeComparer : Comparer<DateTime>
{
private Prescision _Prescision;
public enum Prescision : sbyte
{
Millisecons,
Seconds,
Minutes,
Hour,
Day,
Month,
Year,
Ticks
}
Func<DateTime, DateTime>[] actions = new Func<DateTime, DateTime>[]
{
(x) => { return x.AddMilliseconds(-x.Millisecond);},
(x) => { return x.AddSeconds(-x.Second);},
(x) => { return x.AddMinutes(-x.Minute);},
(x) => { return x.AddHours(-x.Hour);},
(x) => { return x.AddDays(-x.Day);},
(x) => { return x.AddMonths(-x.Month);},
};
public DateTimeComparer(Prescision prescision = Prescision.Ticks)
{
_Prescision = prescision;
}
public override int Compare(DateTime x, DateTime y)
{
if (_Prescision == Prescision.Ticks)
{
return x.CompareTo(y);
}
for (sbyte i = (sbyte)(_Prescision - 1); i >= 0; i--)
{
x = actions[i](x);
y = actions[i](y);
}
return x.CompareTo(y);
}
}
Run Code Online (Sandbox Code Playgroud)
用法示例:
new DateTimeComparer(DateTimeComparer.Prescision.Day).Compare(Date1, Date2)
Run Code Online (Sandbox Code Playgroud)