Noobster Noobster - 1 year ago 116
C# Question

Time string to a different DateTime format in c#

I am inserting time via this

timeDepartureArray[i] = timeDeparture.Text.ToString();

and it is formatted as
h:mm tt
this is a string. How can I fetch again that string to turn it into a


I really don't know how to stress out my question more. That is really my question. The time I'm outputting is set to
, so I want to fetch that
and display it again as a
. How can that be so hard?

Answer Source

Assuming timeDeparture.Text has Format h:mm tt like 9:10 pm, you have to parse it first into DateTime and use .ToString() to bring it into the desired 24h format.

In .NET h is for 12h format and H represents 24h format.

string timeDeparture = "10:30 PM";
DateTime parsedResult = DateTime.ParseExact(timeDeparture, "h:mm tt", System.Globalization.CultureInfo.InvariantCulture);
string result = parsedResult.ToString("H:mm"); // H for 24 hour
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download