简体   繁体   English

如何确定日期是否在C#中的日期范围内?

[英]How can I determine if a date is within a range of dates in C#?

I am attempting to write code to perform specific actions if the entered date is between January and April, but I cannot come up with a valid comparison for the two. 如果输入的日期介于一月和四月之间,我试图编写代码以执行特定的操作,但是我无法对两者进行有效的比较。 Using TryParse would not change my string into an appropriate format, and the two types cannot be compared without some form of parsing. 使用TryParse不会将我的字符串更改为适当的格式,并且如果没有某种形式的解析,就无法比较这两种类型。 This is what I am working with so far: 到目前为止,这是我正在使用的:

if (dtpCheckIn >= TryParse("1/1/2016") && dtpCheckIn < TryParse("5/1/2016")
{
    //Do Something
}
    var startDate = new DateTime(2016, 1, 1);

    var endDate = new DateTime(2016, 5, 1);   

    var checkInIsValid = dtpCheckIn >= startDate && dtpCheckIn < endDate; 
// i saw that your start, end date are previously defined

If you don't have a custom method as TryParse , this method belongs on DateTime structure and you can use it as DateTime.TryParse . 如果没有自定义方法TryParse ,则此方法属于DateTime结构,可以将其用作DateTime.TryParse But even if you do, this method takes string as a first parameter and takes out as a second one (generally using that overload). 但是, 即使您这样做,此方法也将string作为第一个参数,并将out作为第二个参数(通常使用该重载)。 And it returns true or false as your string can be parsed or not. 它返回truefalse因为您的字符串可以解析或无法解析。 It does not return a DateTime . 返回DateTime

I assume your dtpCheckIn already a DateTime , you can easily use < and >= operators for comparing other DateTime instances. 我假设您的dtpCheckIn 已经是一个DateTime ,您可以轻松地使用<>=运算符来比较其他DateTime实例。

The right syntax can be like; 正确的语法可以像;

if (dtpCheckIn >= new DateTime(2016, 1, 1) && dtpCheckIn < new DateTime(2016, 5, 1))
{
}

Take a look at 看一眼

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

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