Operator '!=' cannot be applied to operands of type 'DateTime' and 'string'

I have a C# Console Application that gets the Wednesday of the third Tuesday of the month, which works perfectly.

The issue?

I want to convert DateTime only to check the date rather than the date with the time.

So, if dd-MM-yyyy is equal to day variable (check current code below), do something rather than if dd-MM-yyyy 12:00:00 AM is equaled to day

Current Working Code

DateTime day = new(DateTime.Now.Year, DateTime.Now.Month, 1);
            

            switch (day.DayOfWeek)
            {
                case DayOfWeek.Sunday:
                    day.AddDays(17);
                    break;

                case DayOfWeek.Monday:
                    day.AddDays(16);
                    break;

                case DayOfWeek.Tuesday:
                    day.AddDays(15);
                    break;

                case DayOfWeek.Wednesday:
                    day.AddDays(21);
                    break;

                case DayOfWeek.Thursday:
                    day.AddDays(20);
                    break;

                case DayOfWeek.Friday:
                    day.AddDays(19);
                    break;

                case DayOfWeek.Saturday:
                    day.AddDays(18);
                    break;
            }


            if (DateTime.Now != day)
            {
                //Do something here
            }
            else
            {
                //Do something here
            }

What I tried doing and received an error – Operator ‘!=’ cannot be applied to operands of type ‘DateTime’ and ‘string’

if (DateTime.Now != day.ToString("dd-MM-YYYY"))
            {
                //Do something here
            }
            else
            {
                //Do Something here
            }

Overall, I want the program to detect the Date portion of the DateTime class and do something if that date matches. How would I go about doing this?

Also, I do not want to print out the Date in the output if my words get misinterpreted.

>Solution :

It makes no sense to convert a DateTime to a string in order to compare it to a DateTime.

Use this instead:

if (DateTime.Now.Date != day.Date)

And you can simplify it to:

if (DateTime.Today != day.Date)

.Date will give you the value of the DateTime but with the time component zeroed out (i.e. midnight). DateTime.Today is equivalent to DateTime.Now.Date.

Leave a Reply