Question

I want to compare to dates like :

I have an Variable DateTime, and I want compare if the TIME of this variable is smaller than actual TIME ...

ex:

 Datetime DateT = new DateTime.Now; 

    string Myvariable = "13:00:36";
Was it helpful?

Solution

You can use DateTime.TryParseExact Method and DateTime.TimeOfDay Property as below

string value = "13:00:36";
DateTime dt;
if (DateTime.TryParseExact(value, "HH:mm:ss", CultureInfo.InvariantCulture,
                        DateTimeStyles.None, out dt))
{
    if (dt.TimeOfDay > DateTime.Now.TimeOfDay)
    {
        // greater than actual time 
    }
    else
    {
        // smaller than actual time
    }
}

Since you have time in string format it is difficult to compare. What you can do is convert it to Datetime by giving correct format string. Now you have two DateTime objects and you can get Time of those object by TimeOfDay property and compare..

OTHER TIPS

Have you tried to use the DateTime variable instead? Something like this:

DateTime date1 = new DateTime(2013, 1, 1, 13, 00, 36);
DateTime dateNow = new DateTime.Now;

Console.WriteLine(date1.ToString("T", CultureInfo.CreateSpecificCulture("es-ES")));
// Outputs 6:30:00
Console.WriteLine(date1.ToString("U", CultureInfo.CreateSpecificCulture("en-US")));
// Outputs Tuesday, January 1, 2013 13:00:36 PM 
Console.WriteLine(dateNow.ToString());
// Outputs the current date/time

Then you can create another DateTime and compare them as DateTime variable, not strings, although you can still output the values as strings using date1.ToString() function.

More info about it here: http://msdn.microsoft.com/en-us/library/az4se3k1.aspx

Hope it helps.

Use the following code to get the time string as a DateTime instance:

 DateTime DateT = new DateTime.Now; 

 string Myvariable = "13:00:36";

 DateTime parsedTime = DateTime.ParseExact(
    Myvariable, 
    "HH:mm:ss", 
    CultureInfo.InvariantCulture);

The parsedTime will have the time components (Hour, Minute, Second) as given in the string variable, but it will have a different date. The Year, Month and Day components are not present in the string, so they will default to the date of DateTime.MinValue.Date. In order to compare correctly, you need to compare only the time parts:

bool isParsedGreater = parsedTime.Hours > DateT.Hours 
    && parsedTime.Minutes > DateT.Minutes 
    && parsedTime.Seconds > DateT.Seconds;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top