Anil Gadiyar
Anil Gadiyar

Reputation: 397

DateTime compare in c# when i try to compare next year datetime

I am comparing a user given date with system.datetime in c# if the date is passed or if the date matches the system.date time it is considered

if ((Convert.ToDateTime(firstTimeOFArray).ToString(@"MM\/dd\/yyyy HH:mm").CompareTo(System.DateTime.Now.ToString(@"MM\/dd\/yyyy HH:mm")) == 0 ||
     Convert.ToDateTime(firstTimeOFArray).ToString(@"MM\/dd\/yyyy HH:mm").CompareTo(System.DateTime.Now.ToString(@"MM\/dd\/yyyy HH:mm")) == -1))
{
    filenamedate = DR_FILENAME;
    fileFound = true;
}

my problem is if i give a date like 2016/12/22 3:00 pm it will accept it at exact 2016/12/22 3:00 pm at system time.

if the time is already passed like ex: system time is 2016/12/22 3:00 pm and user time is 2016/12/21 3:00 pm. the logic is accept.

but if i give the system time 2016/12/21 3:00 pm and user time 2017/12/21 3:00 pm.. it again accepts. ideally it should not until the sytem goes to that exact date in 2017. where am i going wrong.

Upvotes: 0

Views: 172

Answers (1)

Ondrej Tucny
Ondrej Tucny

Reputation: 27962

Replace this:

if ((Convert.ToDateTime(firstTimeOFArray).ToString(@"MM\/dd\/yyyy HH:mm").CompareTo(System.DateTime.Now.ToString(@"MM\/dd\/yyyy HH:mm")) == 0 ||
     Convert.ToDateTime(firstTimeOFArray).ToString(@"MM\/dd\/yyyy HH:mm").CompareTo(System.DateTime.Now.ToString(@"MM\/dd\/yyyy HH:mm")) == -1))

with this:

if (Convert.ToDateTime(firstTimeOFArray) <= DateTime.Now)

which is probably what you meant. From then it will be much easier for you to understand the sematics of your own code and achieve what you want.

Note that for lexicographic comparison of string representations of two DateTimes would need the yyyy MM dd HH mm sequence of components in order to work.

Upvotes: 2

Related Questions