如何截断毫秒掀起了.NET日期时间 [英] How to truncate milliseconds off of a .NET DateTime

查看:195
本文介绍了如何截断毫秒掀起了.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
...

这篇关于如何截断毫秒掀起了.NET日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆