确定日期时间值的平等内LINQ分钟精度 [英] Determine equality of Datetime values with minute precision within LINQ

查看:231
本文介绍了确定日期时间值的平等内LINQ分钟精度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要比较两个日期时间值,以确定相等(完全相同),利用微小precision.Would这是做到这一点的最好方法是什么?我的日期可能有秒和毫秒,但我只想下来,直到分钟考虑。

 其中(Math.Abs​​(datetime1。减去(DATETIME2).TotalMinutes)== 0)


解决方案

检查是否 Math.Abs​​(diff.TotalMinutes)== 0 不会做它,没有 - 这是检查是否他们的究竟的相同



您尝试检查它们是否具有相同的一刻,或者他们是否是相距超过一分钟的时间?对于一,用途:

 其中RoundToMinute(dateTime1)== RoundToMinute(DATETIME2)

已宣布:

 公共静态的DateTime RoundToMinute(DateTime的时间)
{
返回新的datetime(time.Year,time.Month,time.Day,
time.Hour,time.Minute,0,time.Kind);
}



对于第二个,使用:

 其中Math.Abs​​((dateTime1  -  DATETIME2).TotalMinutes)LT; 1 

您应该考虑你想要的结果是在的情况下,一个是本地,一个是什么在UTC,顺便...



请注意,有什么具体的LINQ在这里 - 假设你使用LINQ到对象。如果你正在使用LINQ to SQL,那显然你不能使用本地方法,我们将不得不再次审视...



编辑:我还是很清楚你的问题。如果你需要他们的究竟的同一日期/时间,很容易(撇开可能的地方VS UTC的问题):

 ,其中dateTime1 == DATETIME2 

不过,回避了为什么你的问题提到在问题的标题或身体问题,用一分钟的精度,精分。


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)

解决方案

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.

这篇关于确定日期时间值的平等内LINQ分钟精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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