Determine equality of Datetime values with minute precision within LINQ

爱⌒轻易说出口 提交于 2020-01-02 03:09:51

问题


I need to compare two datetime values to determine equality(exactly the same),using minute precision.Would this be the best way to do it? My dates could have seconds and milliseconds, but i want to consider only down till minutes.

       where (Math.Abs(datetime1.Subtract(datetime2).TotalMinutes) == 0)

回答1:


Checking whether Math.Abs(diff.TotalMinutes) == 0 won't do it, no - that's checking whether they're exactly the same.

Are you trying to check whether they have the same minute, or whether they're less than a minute apart? For the first, use:

where RoundToMinute(dateTime1) == RoundToMinute(dateTime2)

having declared:

public static DateTime RoundToMinute(DateTime time)
{
    return new DateTime(time.Year, time.Month, time.Day,
                        time.Hour, time.Minute, 0, time.Kind);
}

For the second, use:

where Math.Abs((dateTime1 - dateTime2).TotalMinutes) < 1

You should consider what you want the result to be in the case that one is local and one is in UTC, by the way...

Note that there's nothing LINQ-specific here - assuming you're using LINQ to Objects. If you're using LINQ to SQL, then obviously you can't use local methods, and we'll have to look again...

EDIT: I'm still very unclear on your question. If you need them to be exactly the same date/time, it's easy (leaving aside the possible local vs UTC issue):

where dateTime1 == dateTime2

However, that begs the question of why you mention "minute precision" in the question title or "using up to a minute precision" in the question body.




回答2:


How about

where (Math.Floor(datetime1.Ticks / 600000000) == Math.Floor(datetime2.Ticks / 600000000))

?




回答3:


Thanks Allen,will do that(still figuring out exactly how the process works!).Here is the code snippet indicating the answer i had come up with initially:

(Math.Abs(datetime1.Subtract(datetime2).TotalMinutes) == 0)

Background: Within my linq query's WHERE clause(hence a one-liner), I need to check if datetime1 and datetime2 are exactly the same. The datetime values under consideration are stamp dates for other values used in the query.



来源:https://stackoverflow.com/questions/1256460/determine-equality-of-datetime-values-with-minute-precision-within-linq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!