如何检查C#DateTime是否在一个范围内 [英] How to check whether C# DateTime is within a range

查看:410
本文介绍了如何检查C#DateTime是否在一个范围内的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中,我有 DateTime值,并且想检查一个 DateTime是否在该范围内,我该怎么做这个?

In C# I have from and to DateTime vales and want to check whether a value DateTime is within the range, how can I do this?

lowerBound = "01-Dec-2011 09:45:58"
upperBound = "01-Dec-2011 09:38:58"
value = "01-Dec-2011 09:49:58"


推荐答案

只需使用比较运算符,就像使用数字:

Just use the comparison operators as you would for numbers:

DateTime lowerBound = new DateTime(2011, 12, 1, 9, 38, 58);
DateTime upperBound = new DateTime(2011, 12, 1, 9, 49, 58);
DateTime value = new DateTime(2011, 12, 1, 9, 45, 58);

// This is an inclusive lower bound and an exclusive upper bound.
// Adjust to taste.
if (lowerBound <= value && value < upperBound)

你我们需要注意的是,所有的值都是一样的(UTC,本地,非特定的)。如果您想要及时比较 instants (例如X在Y之前发生),最好使用UTC。

You'll need to be careful that the values are all the same "kind" (UTC, local, unspecific). If you're trying to compare instants in time, (e.g. "did X happen before Y") it's probably best to use UTC.

这篇关于如何检查C#DateTime是否在一个范围内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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