Home
Map
DayOfWeekUse the DayOfWeek enum type, which contains Monday, Tuesday, Wednesday, Thursday, Friday, Saturday and Sunday.
C#
This page was last reviewed on Dec 13, 2022.
DayOfWeek. 7 days are in each week. In C# programs we can determine if a certain date is a Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, or Sunday.
Shows a property
The DayOfWeek property, and the DayOfWeek enum type, can be used for this purpose. These 2 types have the same name, but are different (and often used together).
enum
DateTime
Initial example. To begin, we look at a program that acquires the current DayOfWeek. You can use either DateTime.Now or DateTime.Today to get the current day.
Then You can take the DayOfWeek from the DateTime instance. DayOfWeek is a property, and also an enum type.
DateTime.Now
Next We use if or switch on a DayOfWeek. We test what day of the week was found using an if-expression.
And In the example output, the DO WORK line only appears if the program was run on a Monday.
Finally We print (with Console.WriteLine) all the values of the DayOfWeek enum for completeness.
Shows a property
using System; class Program { static void Main() { // Get current day of week. DayOfWeek today = DateTime.Today.DayOfWeek; Console.WriteLine("Today is {0}", today); // Test current day of week. if (today == DayOfWeek.Monday) { Console.WriteLine("DO WORK"); } // Demonstrate all DayOfWeek values. Console.WriteLine("{0}, {1}, {2}, {3}, {4}, {5}, {6}", DayOfWeek.Monday, DayOfWeek.Tuesday, DayOfWeek.Wednesday, DayOfWeek.Thursday, DayOfWeek.Friday, DayOfWeek.Saturday, DayOfWeek.Sunday); } }
Today is Monday DO WORK Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday
Day list. We can use DayOfWeek in collections like a list. We do not need to use the DayOfWeek property in the same program as the DayOfWeek enum.
Here We use the DayOfWeek enum to represent work days in a List. We then loop over and print the day names.
List
foreach
using System; using System.Collections.Generic; class Program { static void Main() { // Use a DayOfWeek list. List<DayOfWeek> workDays = new List<DayOfWeek>(); workDays.Add(DayOfWeek.Monday); workDays.Add(DayOfWeek.Wednesday); // Loop over list of days. foreach (var day in workDays) { Console.WriteLine($"WORK DAY: {day}"); } } }
WORK DAY: Monday WORK DAY: Wednesday
A summary. The DayOfWeek enum is a convenient type for representing the day of the week as a small value. This type can be used anywhere.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
No updates found for this page.
Home
Changes
© 2007-2024 Sam Allen.