Check if dateTime is a weekend or a weekday

前端 未结 6 1905
日久生厌
日久生厌 2021-02-03 20:48


        
6条回答
  •  野性不改
    2021-02-03 21:24

    You are receiving an error because you are comparing an enum with a string.

    // dayToday is a string
    // DayOfWeek.Saturday is an enum
    if ((dayToday == DayOfWeek.Saturday) && (dayToday == DayOfWeek.Sunday))
    

    Use DayOfWeek.Saturday.ToString() to compare against a string. You will also want not to pad the dayToday string. Alternatively, use the day variable to compare against an enum.

    https://dotnetfiddle.net/gUGJ0J

    using System;
    
    public class Program
    {
        public static void Main()
        {
            DateTime date = DateTime.Now;
    
            string dateToday = date.ToString("d");
            DayOfWeek day = DateTime.Now.DayOfWeek;
            string dayToday = day.ToString();
    
            // compare enums
            if ((day == DayOfWeek.Saturday) || (day == DayOfWeek.Sunday))
            {
                Console.WriteLine(dateToday + " is a weekend");
            }
            else
            {
                Console.WriteLine(dateToday + " is not a weekend");
            }
    
            // compare strings
            if ((dayToday == DayOfWeek.Saturday.ToString()) || (dayToday == DayOfWeek.Sunday.ToString()))
            {
                Console.WriteLine(dateToday + " is a weekend");
            }
            else
            {
                Console.WriteLine(dateToday + " is not a weekend");
            }
        }
    }
    

提交回复
热议问题