简体   繁体   中英

day of week and hour of day in a if statement c#

I want to do something if the day, and time of the day equal true in a if statement. I have the day part down, just can't figure out the time part out. Let say I wan the time to be 9AM.

Here is what I have so far

var dt_check_monday = DateTime.Now.DayOfWeek;
if (dt_check_monday == DayOfWeek.Monday && time_now = DateTime.Now.Hour==9)
{
//do something
}

I can't use this I get an error:

Operator '&&' cannot be applied to operands of type 'bool' and 'System.TimeSpan'

Thanks for any help in advance.

= is an assignment. == is the 'equals'

Your second = should be a ==

You should just do this:

if (DateTime.Now.DayOfWeek == DayOfWeek.Monday && DateTime.Now.Hour == 9)
{

}

Your code has an assignment to an undeclared variable time_now and you're doing an assignment time_now = which is what's causing it to fail.

You should also consider revising how you name your variables, dt_check_monday means absolutely nothing if the value inside it is DayOfWeek.Wednesday , consider changing it to something like dt_currentDayOfWeek but that already exists in the form of DateTime.Now.DayOfWeek which is why I dropped the variable from my example.

If you want to keep time_now for later use, you have to encase the assignment in the if-statement with paratheses.

var dt_check_monday = DateTime.Now.DayOfWeek;
if (dt_check_monday == DayOfWeek.Monday && (time_now = DateTime.Now.Hour) == 9)
{
    //do something
}

I think time_now is having TimeSpan datatype. So you can try this

if (dt_check_monday == DayOfWeek.Monday && time_now.Hours == 9)
 {
    //do something
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM