Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if dateTime is a weekend or a weekday

Tags:

c#

datetime

<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.

like image 513
penmas Avatar asked Sep 27 '16 04:09

penmas


People also ask

How do you check a date is Saturday or Sunday in C#?

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 .

Does Python have weekday or weekend?

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.

How do I check if a date is Saturday or Sunday in Python?

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.


2 Answers

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"); } 
like image 131
Farid Imranov Avatar answered Sep 21 '22 17:09

Farid Imranov


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)) 
like image 25
DAXaholic Avatar answered Sep 23 '22 17:09

DAXaholic