如何截断 .NET DateTime 的毫秒数 [英] How to truncate milliseconds off of a .NET DateTime

查看:37
本文介绍了如何截断 .NET DateTime 的毫秒数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将来自传入请求的时间戳与数据库存储值进行比较.SQL Server 当然在时间上保持一定的毫秒精度,当读入 .NET DateTime 时,它​​包括这些毫秒.然而,系统的传入请求并没有提供这种精度,所以我需要简单地删除毫秒.

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#).

推荐答案

以下内容适用于具有小数毫秒的 DateTime,并且还保留了 Kind 属性(Local、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
    );

或等价的和更短的:

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
    if (dateTime == DateTime.MinValue || dateTime == DateTime.MaxValue) return dateTime; // do not modify "guard" values
    return dateTime.AddTicks(-(dateTime.Ticks % timeSpan.Ticks));
}

用法如下:

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 DateTime 的毫秒数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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