Noobster Noobster - 11 days ago 5
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
DateTime
like
H:mm


EDIT:

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
string
, so I want to fetch that
string
and display it again as a
datetime
. How can that be so hard?

Answer

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
Comments