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
praveenuniAsked:
Who is Participating?
 
Fahad MukhtarDistinguished 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");  
0
 
mrichmonCommented:
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
0
 
praveenuniAuthor 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 ?
0
Cloud Class® Course: Microsoft Exchange Server

The MCTS: Microsoft Exchange Server 2010 certification validates your skills in supporting the maintenance and administration of the Exchange servers in an enterprise environment. Learn everything you need to know with this course.

 
Bob LearnedCommented:
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
0
 
mrichmonCommented:
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;
0
 
junglerover77Commented:
       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
0
 
Fahad MukhtarDistinguished EngineerCommented:
oops that spanned to 2 lines..
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.