Nicky Name
Nicky Name

Reputation: 101

How to compare 2 DateTime instances in C#?

HELP! Who knows how to compare DateTime objects. For example:

    Dictionary<DateTime, Person> _birthdays;

Then I add bunch of elements to the list, and want to find a person with the date 13. March 1995.

   if(_birthdays.Keys.Contains(new DateTime(13,3,1995))

blah blah ... And it always returns false ofcourse, because it is a whole new instance of DateTime and it probably has hours, seconds etc etc.... I want to compare YEAR MONTH DAY onlyyyy! Please help, it would make my code much simpler!

Upvotes: 0

Views: 73

Answers (1)

Rob Lyndon
Rob Lyndon

Reputation: 12661

The Date struct has a Date member, which gives you just the date.

var targetDate = new DateTime(13,3,1995);

if (_birthdays.Keys.Any(b => b.Date == targetDate))
....

Upvotes: 1

Related Questions