Say now is 13:12 PM and I want to see if it is earlier than 20:00 PM.... I get the current time using DateTime.Now
but I format it as "h:mm tt" and I want to see if a given current time is say between 8:00 AM and 20:00 PM.
Asked
Active
Viewed 76 times
0
-
20:00 PM is not a valid representation of time. What have you tried so far? – Liu Mar 25 '17 at 11:46
3 Answers
0
You can compare the DateTime
objects directly r use the Ticks
property to compare them. Below is a simple example demonstrating that
var dt1 = DateTime.ParseExact("8:00:00", "H:mm:ss", null);
var dt2 = DateTime.ParseExact("20:00:00", "H:mm:ss", null);
if (dt1 <= DateTime.Now && dt2 >= DateTime.Now)
Console.WriteLine("Hooray");

Vikhram
- 4,294
- 1
- 20
- 32
-
not working... I used it like this: `var dt1 = DateTime.Parse("8:00:00"); var dt2 = DateTime.Parse("20:00:00"); if (dt1 <= DateTime.Now && DateTime.Now >= dt2) MessageBox.Show(DateTime.Now.ToString("h:mm tt")); else MessageBox.Show("No.");` current time here is: 13:32 PM – Mar 25 '17 at 11:32
-
@A.Ispas Not sure why it did not work for you, since it worked for me. My guess would be your locale settings are different than mine. I edited the answer to use `ParseExact`. Please try that. If that does not work, can you show the output of `DateTime.Now.ToString()` for you. Your focus should be actually on the `if` line and not the other lines – Vikhram Mar 25 '17 at 11:44
-
`if(DateTime.Now.Hour > 8 && DateTime.Now.Hour < 20) { MessageBox.Show("hooray"); }` it works like this so its okay now. I figured it out. Thanks. – Mar 25 '17 at 11:48
0
The code goes as under:
DateTime dtFrom = DateTime.Now.Date.AddHours(8); // Use Current Date and set time to 8:00 AM
DateTime dtUpto = DateTime.Now.Date.AddHours(20); // Use Current Date and set time to 20:00 (8:00 PM)
DateTime dtCurr = DateTime.Now;
if (dtFrom <= dtCurr && dtCurr <= dtUpto)
MessageBox.Show(dtCurr.ToString("h:mm tt"));
else
MessageBox.Show("No");

Rupesh
- 242
- 2
- 6
-
if(DateTime.Now.Hour > 8 && DateTime.Now.Hour < 20) { MessageBox.Show("hooray"); } it works like this so its okay now. I figured it out. Thanks. – Mar 25 '17 at 11:48
0
Please you can check this way:
DateTime dt1;
dt1 = DateTime.Parse("8:00:00");
DateTime dt2;
dt2 = DateTime.Parse("20:00:00");
if (dt1 <= DateTime.Now && DateTime.Now >= dt2)
{
MessageBox.Show(DateTime.Now.ToString("h:mm tt"));
}
else MessageBox.Show("No.");

anis programmer
- 989
- 1
- 10
- 25
-
`if(DateTime.Now.Hour > 8 && DateTime.Now.Hour < 20) { MessageBox.Show("hooray"); }` it works like this so its okay now. I figured it out. Thanks. – Mar 25 '17 at 11:48