J. Doe
J. Doe

Reputation: 23

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
}

Upvotes: 0

Views: 112

Answers (2)

Soner G&#246;n&#252;l
Soner G&#246;n&#252;l

Reputation: 98750

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

Upvotes: 2

Razvan Dumitru
Razvan Dumitru

Reputation: 12452

    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

Upvotes: 2

Related Questions