<script Language="c#" runat="server"> void Page_Load() { DateTime date = DateTime.Now; dateToday.Text = " " + date.ToString("d"); DayOfWeek day = DateTime.Now.DayOfWeek; dayToday.Text = " " + day.ToString(); if ((dayToday == DayOfWeek.Saturday) && (dayToday == DayOfWeek.Sunday)) { Console.WriteLine("This is a weekend"); } } </script>
Using dateTime, I am trying to test whether or not the current date is a weekday or weekend, then I would like to print the response to the user. Currently I am receiving a Runtime Error. If I remove my if statement the first items (the current date, and the day of the week) print properly.
By using the DateTime type, we automatically get access to the property called DayOfWeek . The value for DayOfWeek will always be one of the seven days in a week, from Monday to Sunday. There is no need to redefine the seven days, the C# package comes with an enum for them, with a suggestive name – DayOfWeek .
To check if a day is weekday or weekend in Python, we basically get the day number using weekday() function and see if it's > 4 or <4. Easy! from datetime import datetime d = datetime(2020, 12, 25); if d. weekday() > 4: print 'Given date is weekend.
We can use the weekday() method of a datetime. date object to determine if the given date is a weekday or weekend. Note: The weekday() method returns the day of the week as an integer, where Monday is 0 and Sunday is 6. For example, the date(2022, 05, 02) is a Monday.
You wrote wrong varable in the following if statement:
if ((dayToday == DayOfWeek.Saturday) || (dayToday == DayOfWeek.Sunday)) { Console.WriteLine("This is a weekend"); }
instead of dayToday you must use day varable in the condition.
UPDATE: Also you made mistake in condition. There must be or
instead of and
.
Correct code is
if ((day == DayOfWeek.Saturday) || (day == DayOfWeek.Sunday)) { Console.WriteLine("This is a weekend"); }
You are comparing your ASP.NET label dayToday
against an enumeration element of DayOfWeek
which of course fails
Probably you want to replace dayToday
with day
in your if
statement, i.e. from
if ((dayToday == DayOfWeek.Saturday) && (dayToday == DayOfWeek.Sunday))
to
if ((day == DayOfWeek.Saturday) && (day == DayOfWeek.Sunday))
In addition, you probably also want to replace the logical 'and' (&&
) with a logical 'or' (||
) to finally
if ((day == DayOfWeek.Saturday) || (day == DayOfWeek.Sunday))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With