C#: DateTime.DayOfWeek to string comparison

前端 未结 4 1985
长发绾君心
长发绾君心 2020-12-04 01:47

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         


        
4条回答
  •  春和景丽
    2020-12-04 02:14

    Easiest is to convert enum to string:

    if (day == dt.DayOfWeek.ToString())...
    

    Notes:

    • if you can change type of day to DayOfWeek enum you can avoid string comparisons (and its related localization/comparison issues).
    • if you have to use string make sure to decide if case is important or not (i.e. should "thursday" be equal to DayOfWeek.Thursday) and use corresponding String.Equals method.
    • consider converting string to enum with Parse as suggested in other answers: ((DayOfWeek)Enum.Parse(typeof(DayOfWeek), day)
    • make sure incoming string is always English - if it could be in other languages you'll need to look into manually matching value to one provided in CultureInfo.DateTimeFormat.DayNames.

提交回复
热议问题