简体   繁体   中英

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. 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 . But even if you do, this method takes string as a first parameter and takes out as a second one (generally using that overload). And it returns true or false as your string can be parsed or not. It does not return a DateTime .

I assume your dtpCheckIn already a DateTime , you can easily use < and >= operators for comparing other DateTime instances.

The right syntax can be like;

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

Take a look at

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