# Find Current Time

Hello

I have 2 values 5:30PM and 6:30PM

Using C# How will I know if the current time is between these 2 times ?

Thanks
###### Who is Participating?

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Commented:
You can do a comparison to DateTime.Now.TimeOfDay

or if you have those values in a date/time object you can do a simple date/time comparison to DateTime.Now
Author Commented:
I know what to do (i mean the algorithm) but I'm unable to put it in c# terms. Can you please help me ?
Commented:
Try this:

private void Form1_Load(object sender, System.EventArgs e)
{

TimeSpan start = new TimeSpan(17, 30, 0);
TimeSpan end = new TimeSpan(18, 30, 0);

MessageBox.Show(NowInTimeRange(start, end);

}

public static bool NowInTimeRange(TimeSpan start, TimeSpan end)
{
TimeSpan now = new TimeSpan(DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second);

TimeSpan test1 = now.Subtract(start);
TimeSpan test2 = end.Subtract(now);

return (test1.TotalSeconds > 0 && test2.TotalSeconds > 0);

}

Bob
Commented:
Assuming hte time is in string format

string firstTime = "5:30PM";
string secondTime = "6:30PM";

DateTime firstDateTime = Convert.ToDateTime("1/1/2005 " + firstTime);
DateTime secondDateTime = Convert.ToDateTime("1/1/2005 " + secondTime);

if(DateTime.Now.TimeOfDay <= secondDateTime.TimeofDay && DateTime.Now.TimeOfDay >= firstDateTime)
return true;
else
return false;
Commented:
private bool CheckTime()
{
TimeSpan ts1 = new TimeSpan(17, 30, 0);
TimeSpan ts2 = new TimeSpan(18, 30, 0);

if (ts1 < DateTime.Now.TimeOfDay && DateTime.Now.TimeOfDay < ts2) return true;
else return false;
}

Jungle
Distinguished EngineerCommented:
How about a single line check using DateTime.Compare() Method
if ((DateTime.Compare(DateTime.Parse("5:30 PM"), DateTime.Now)<=0) && (DateTime.Compare(DateTime.Parse("6:30 PM"), DateTime.Now)>=0))
MessageBox.Show("Current Time Between 5:30PM and 6:30PM");

Experts Exchange Solution brought to you by