简体   繁体   中英

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:

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. DateTime comparisons only compare to the nearest second which isn't accurate enough.

How do I compare the two values in the LINQ statement to the millisecond?

You can retrieve the total Milliseconds of a DateTime object in C#. 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.

This isn't true. It's depending on your data type of your DateTime column. Choose the datetime2 data type for more accuracy.

See the SQL below.

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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