如何截断毫秒掀起了.NET日期时间
我想从传入请求数据库存储值进行比较时间戳。当然,SQL Server保留的时间毫秒的一些precision,当读入一个.NET日期时间,它包括那些毫秒。到达请求到该系统,但是,没有提供的precision,所以我需要简单地丢弃毫秒。
I'm trying to compare a time stamp from an incoming request to a database stored value. SQL Server of course keeps some precision of milliseconds on the time, and when read into a .NET DateTime, it includes those milliseconds. The incoming request to the system, however, does not offer that precision, so I need to simply drop the milliseconds.
我觉得我失去了一些东西很明显,但我还没有找到一种优雅的方式来做到这一点(C#)。
I feel like I'm missing something obvious, but I haven't found an elegant way to do it (C#).
下面的工作的日期时间,有小数毫秒,也preserves Kind属性(本地,UTC或undefined)。
The following will work for a DateTime that has fractional milliseconds, and also preserves the Kind property (Local, Utc or Undefined).
DateTime dateTime = ... anything ...
dateTime = new DateTime(
dateTime.Ticks - (dateTime.Ticks % TimeSpan.TicksPerSecond),
dateTime.Kind
);
或同等及更短的:
or the equivalent and shorter:
dateTime = dateTime.AddTicks( - (dateTime.Ticks % TimeSpan.TicksPerSecond));
这可以概括为一个扩展方法:
This could be generalized into an extension method:
public static DateTime Truncate(this DateTime dateTime, TimeSpan timeSpan)
{
if (timeSpan == TimeSpan.Zero) return dateTime; // Or could throw an ArgumentException
return dateTime.AddTicks(-(dateTime.Ticks % timeSpan.Ticks));
}
它用于如下:
which is used as follows:
dateTime = dateTime.Truncate(TimeSpan.FromMilliseconds(1)); // Truncate to whole ms
dateTime = dateTime.Truncate(TimeSpan.FromSeconds(1)); // Truncate to whole second
dateTime = dateTime.Truncate(TimeSpan.FromMinutes(1)); // Truncate to whole minute
...