C#: DateTime.DayOfWeek to string comparison

前端 未结 4 1983
长发绾君心
长发绾君心 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:02

    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)
    
    0 讨论(0)
  • 2020-12-04 02:05

    You can use Enum.TryParse<DayOfWeek>:

    string strDay = "Wednesday";
    DayOfWeek day;
    if (Enum.TryParse<DayOfWeek>(strDay, out day)
        && day == DateTime.Today.DayOfWeek)
    {
        // ...
    }
    
    0 讨论(0)
  • 2020-12-04 02:12

    Try DayOfWeek day = DayOfWeek.Thursday;

    0 讨论(0)
  • 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.
    0 讨论(0)
提交回复
热议问题