How to get the integer value of day of week

前端 未结 9 660
太阳男子
太阳男子 2020-12-02 18:15

How do I get the day of a week in integer format? I know ToString will return only a string.

DateTime ClockInfoFromSystem = DateTime.Now;
int day1;
string d         


        
相关标签:
9条回答
  • 2020-12-02 18:19
    int day = (int)DateTime.Now.DayOfWeek;
    

    First day of the week: Sunday (with a value of zero)

    0 讨论(0)
  • 2020-12-02 18:24

    Another way to get Monday with integer value 1 and Sunday with integer value 7

    int day = ((int)DateTime.Now.DayOfWeek + 6) % 7 + 1;
    0 讨论(0)
  • 2020-12-02 18:25

    Use

    day1 = (int)ClockInfoFromSystem.DayOfWeek;
    
    0 讨论(0)
  • 2020-12-02 18:28

    The correct way to get the integer value of an Enum such as DayOfWeek as a string is:

    DayOfWeek.ToString("d")
    
    0 讨论(0)
  • 2020-12-02 18:28

    The correct answer, is indeed the correct answer to get the int value.

    But, if you're just checking to make sure it's Sunday for example... Consider using the following code, instead of casting to an int. This provides much more readability.

    if (yourDateTimeObject.DayOfWeek == DayOfWeek.Sunday)
    {
        // You can easily see you're checking for sunday, and not just "0"
    }
    
    0 讨论(0)
  • 2020-12-02 18:44

    Try this. It will work just fine:

    int week = Convert.ToInt32(currentDateTime.DayOfWeek);
    
    0 讨论(0)
提交回复
热议问题