Home > Software engineering >  Operator '==' cannot be applied to operands of type 'DateTime' and 'string&
Operator '==' cannot be applied to operands of type 'DateTime' and 'string&

Time:08-27

In c#, I am trying to compare the current day with the day the user has chosen from the checkboxes via the website. CDays contains the list Mon-Fri (Name) and Selected will be true if the user has checked the current days' checkbox. For example today is Friday, if the user has checkboxed Friday on the website return true.

I am running into Operator '==' cannot be applied to operands of type 'DateTime' and 'string' and I'm not sure how to convert DateTime to a string

 public List<CDay> days { get; set; }
    public CDay()
    {
     Name = string.Empty; // Monday, Tuesday, Wednesday, Thursday, Friday
     Selected = false; //will be true if user has selected this checkbox
    }
    

my logic:

private bool currentDayOfTheWeek (DateTime now, List <CDay> days)
        {
          now = DateTime.Now;
        
          for (int i = 0; i < days.Count; i  )
          {

            if ( days[i].Selected.Equals(true) && now == days[i].Name) 
                 {
                     return true;
                 }
              }
            return false;
          }

CodePudding user response:

Use the option DayOfTheWeek from 'now' object...

Something like this:

if (now.DayOfWeek == days[i].Name){
//code
}

CodePudding user response:

Please use now.DayOfWeek.ToString() == days[i].Name

  • Related