Reputation: 19
For example, a user can view his password if today is Monday or Tuesday and if his schedule is within the time frame (given), compared to the current system time, but even if Today is Monday or Tuesday, if his given time is, let's say 1:30-5:30PM, and it's not yet or it's already past that time, he won't be able to view his password.
I hope you get the drill. The code below works fine, however, if I put the same day twice, like, Tuesday and Tuesday, there happens to be a conflict. How do I fix this conditional statements? Thanks.
Here's my code:
DateTime systemtime = DateTime.Now;
DateTime timestart = Convert.ToDateTime(txtTimestart.Text);
DateTime timeend = Convert.ToDateTime(txtTimeend.Text);
var systemday = DateTime.Now.DayOfWeek.ToString();
var day1 = Convert.ToString(txtDay1.Text);
var day2 = Convert.ToString(txtDay2.Text);
if (systemday != day1 || systemday != day2)
{
if (systemtime < timestart || systemtime > timeend)
{
MessageBox.Show("You are not authenticated to view your password.", "Get Password Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
else
{
MessageBox.Show("Your password is ...", "Get Password Success", MessageBoxButtons.OK, MessageBoxIcon.None);
return;
}
}
else
{
if (systemtime < timestart || systemtime > timeend)
{
MessageBox.Show("You are not authenticated to view your password.", "Get Password Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
else
{
MessageBox.Show("Your password is ...", "Get Password Success", MessageBoxButtons.OK, MessageBoxIcon.None);
return;
}
}
Upvotes: 0
Views: 965
Reputation: 10840
Taking your example, this line of code means: if current day(system day) is not monday or not tuesday.
if (systemday != day1 || systemday != day2)
Now if today is tuesday then it is not monday which makes first comparison true and it will enter in the if block. if today is monday then it is not tuesday which makes second comparison (Systemday != day2) true. If today is not monday and tuesday then it makes both comparison (systemday != day1 || systemday != day2) true. In short your code will never fall in else.
Now for your problem use
if (systemday == day1 || systemday == day2)
{
if(systemtime>=timestart && systemtime <=timeend)
{
MessageBox.Show("Your password is ...", "Get Password Success", MessageBoxButtons.OK, MessageBoxIcon.None);
return;
}
else
{
MessageBox.Show("You are not authenticated to view your password.", "Get Password Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
Upvotes: 2