This code is a simplified version of what I'm trying to do:
string day = Thursday;
DateTime dt = DateTime.Now;
if (day == dt.DayOfWeek)
{
// start the program
}
I need to read a day of the week value from a database, assign it to a string, then compare the string to dt.DayOfWeek to check if the program should execute.
My error is this: "Operator '==' cannot be applied to operands of type 'string' and 'System.DayOfWeek"
Anyone know how to compare a string to a DateTime.DayOfWeek value?
Use Enum.Parse
to get the Enum value:
if ((DayOfWeek)Enum.Parse(typeof(DayOfWeek), day) == dt.DayOfWeek)
If you're not sure it's a valid value, there's TryParse<T>
:
Enum val;
if (Enum.TryParse<DayOfWeek>(day, out val) && val == dt.DayOfWeek)
Easiest is to convert enum to string:
if (day == dt.DayOfWeek.ToString())...
Notes:
day
to DayOfWeek
enum you can avoid string comparisons (and its related localization/comparison issues).DayOfWeek.Thursday
) and use corresponding String.Equals
method.Parse
as suggested in other answers: ((DayOfWeek)Enum.Parse(typeof(DayOfWeek), day)
Try DayOfWeek day = DayOfWeek.Thursday;
You can use Enum.TryParse<DayOfWeek>
:
string strDay = "Wednesday";
DayOfWeek day;
if (Enum.TryParse<DayOfWeek>(strDay, out day)
&& day == DateTime.Today.DayOfWeek)
{
// ...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With