How to truncate milliseconds off of a .NET DateTime(如何从 .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 中截断毫秒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何从 .NET DateTime 中截断毫秒
基础教程推荐
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 将 XML 转换为通用列表 2022-01-01