Frage

How do I compare which time string is greater; be it in 24-hour or 12-hour format?

For example, "9:42:54" vs "19:25:31" or "9:42:54 AM" vs "7:25:31 PM".

War es hilfreich?

Lösung

To be able to compare strings in time format, you need to convert them to TimeSpan or DateTime objects, but the former seems to be more relevant:

TimeSpan time1 = TimeSpan.Parse("9:42:54");
TimeSpan time2 = TimeSpan.Parse("19:25:31");

or

TimeSpan time1 = DateTime.Parse("9:42:54").TimeOfDay;
TimeSpan time2 = DateTime.Parse("19:25:31").TimeOfDay;

However, using TimeSpan.Parse for 12-hour time string formats will throw a System.FormatException. Use DateTime.Parse instead and take only the time part of the created DateTime object:

TimeSpan time1 = DateTime.Parse("9:42:54 AM").TimeOfDay;
TimeSpan time2 = DateTime.Parse("7:42:54 PM").TimeOfDay;

As a benefit, converting to TimeSpan will also give you a chance to apply TimeSpan operators like regular comparison, subtraction, addition, etc.:

if (time1 > time2)
{
    // time1 is greater
}
else if (time1 < time2)
{
    // time2 is greater
}
else
{
    // They are equal
}

You can also use TimeSpan.ParseExact if you need to the specify the time format of your string explicitly.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top