Click here to Skip to main content
15,886,794 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
DateTime Now = DateTime.Now;
            TimeSpan TS = Now.TimeOfDay;
            String Time1 = Now.ToShortTimeString();
            String Time2 = Now.ToLongTimeString();

            if (timeFrom.CompareTo(timeTo) > 0)
            {
                returnMessage2 += "Time From is bigger than Time To <br />";
            }
Posted
Updated 3-Feb-14 1:10am
v3

Just compare the time of day:
C#
DateTime now = DateTime.Now;
DateTime from = new DateTime(2014, 2, 3, 8, 31, 0);
if (now.TimeOfDay > from.TimeOfDay)
    {
    Console.WriteLine("After FROM time");
    }
 
Share this answer
 
C#
DateTime FromDate = DateTime.Now.AddDays(-1); //2/2/2014 5:41:50 PM
       DateTime ToDate = DateTime.Now.AddDays(2);    //{2/5/2014 5:41:50 PM}
      int value=    DateTime.Compare(ToDate ,FromDate); // 1 means To date is greater
                                                        // -1 lesser
                                                        // 0  equal
 
Share this answer
 
To compare different dates, don't use their string representations, just compare them directly:
C#
DateTime now = DateTime.Now;
DateTime tomorrowSameTime = now + TimeSpan.FromDays(1);

if(tomorrowSameTime > now)
{
    // That's the desired behaviour.
}
else if(tomorrowSameTime < now)
{
    // Something's wrong with the spacetime as we know it.
}
else
{
    // Identical times intentionally ignored.
}
 
Share this answer
 
You are almost right..just change variable name in condition

C#
string returnMessage2 = string.Empty;
            DateTime Now = DateTime.Now;
            TimeSpan TS = Now.TimeOfDay;
            String Time1 = Now.ToLongTimeString();
            String Time2 = Now.ToLongTimeString();
 
            if (Time1.CompareTo(Time2) >= 0)
            {
                returnMessage2 += "Time From is more than Time To, please re-select";
            } 
 
Share this answer
 
v5
Comments
lukeer 3-Feb-14 6:25am    
Why convert to string in the first place when comparing DateTimes works perfectly fine?
Sandeep Singh Shekhawat 3-Feb-14 7:21am    
because op using string..
Richard MacCutchan 3-Feb-14 6:32am    
It is really bad practice to convert numeric types to strings in order to compare them. And in your sample you are using DateTime.Now for both values, so it is obvious they will be the same.
Sandeep Singh Shekhawat 3-Feb-14 7:20am    
Thanks @Richard-MacCutchan
Member 10548723 3-Feb-14 7:02am    
I declare my variables as string, so i need to convert. Can you compare time in string?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900