简体   繁体   English

如何在LINQ查询中将日期时间值与毫秒精度进行比较

[英]How to compare to datetime values to millisecond accuracy in LINQ query

I'm running a fairly straight forward LINQ query that looks like the following: 我正在运行一个相当直接的LINQ查询,如下所示:

List<Event> lstEvents = db.Events.Where(e => e.SystemDatetime <= eventItem.SystemDatetime).ToList();

The SystemDateTime is a DateTime column in the database that stores datetimes in the format yyyy-mm-dd hh:MM:ss.fff. SystemDateTime是数据库中的DateTime列,以yyyy-mm-dd hh:MM:ss.fff格式存储日期时间。 DateTime comparisons only compare to the nearest second which isn't accurate enough. DateTime比较仅与最接近的秒进行比较,但不够准确。

How do I compare the two values in the LINQ statement to the millisecond? 如何将LINQ语句中的两个值与毫秒进行比较?

You can retrieve the total Milliseconds of a DateTime object in C#. 您可以在C#中检索DateTime对象的总毫秒数。 Your existing comparison would then work with the higher accuracy. 然后,您现有的比较将以更高的准确度工作。

List<Event> lstEvents = db.Events.Where(e => e.SystemDatetime.TotalMilliseconds <= eventItem.SystemDatetime.TotalMilliseconds).ToList();

DateTime comparisons only compare to the nearest second which isn't accurate enough. DateTime比较仅与最接近的秒进行比较,但不够准确。

This isn't true. 事实并非如此。 It's depending on your data type of your DateTime column. 这取决于您的DateTime列的数据类型。 Choose the datetime2 data type for more accuracy. 选择datetime2数据类型以获得更高的准确性。

See the SQL below. 请参阅下面的SQL。

DECLARE @datetimes TABLE ([Column1] DATETIME2(7), [Column2] DATETIME2(7))

INSERT INTO
    @datetimes
VALUES
    ('2019-03-26 20:00:00.123', '2019-03-26 20:00:00.124')

SELECT
    *
FROM
    @datetimes
WHERE
    [Column1] <> [Column2]

SELECT
    *
FROM
    @datetimes
WHERE
    [Column1] = [Column2]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM