Time Comparision in C#

G

Guest

Hello Everyone,

How can I compare time in C#.
I have to write that if the current time is less than 9:30 am then exit the
program.

How can i do this programmatically. Right now I am trying to do the code
below, but it doen't work

DateTime dtTime = DateTime.Now;
DateTime timeLimit = new DateTime(dtTime.Year,dtTime.Month, dtTime.Day,
9,30,0);

if ( dtTime < timeLimit)
return;
else

{



}



Thanks.
 
A

Ashot Geodakov

DateTime dt = DateTime.Now;
if( dt.Hour < 9 || ( dt.Hour == 9 && dt.Minute < 30 ) )
{
}
else
{
}
 
G

Guest

Vinki said:
Hello Everyone,

How can I compare time in C#.
I have to write that if the current time is less than 9:30 am then exit the
program.

How can i do this programmatically. Right now I am trying to do the code
below, but it doen't work

DateTime dtTime = DateTime.Now;
DateTime timeLimit = new DateTime(dtTime.Year,dtTime.Month, dtTime.Day,
9,30,0);

if ( dtTime < timeLimit)
return;
else
{

}

Thanks.

Standard question #1:
What do you mean by "not working"?

Your code is just fine. I even tried it to be absolutely sure, and it
works exactly as expected.
 
O

Otis Mukinfus

Standard question #1:
What do you mean by "not working"?

Your code is just fine. I even tried it to be absolutely sure, and it
works exactly as expected.

I agree>

I think perhaps the problem is that when you do something like that in the
Form.Load event you cannot just say return as you did in the sample you gave us.
Doing so will only abort the load event. It will not close the form
(Application).

I think what you want is below:

if ( dtTime < timeLimit)
Application.Exit();
else
{

}



Good luck with your project,

Otis Mukinfus

http://www.otismukinfus.com
http://www.arltex.com
http://www.tomchilders.com
http://www.n5ge.com
 
M

Morten Wennevik [C# MVP]

You could also put the check in the Main method, before the application is created.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top