moe
moe

Reputation: 5249

how to convert time in string format into date time format using C#

i have textbox that accepts time format like this 12:40 PM but would like to convert it into time format like this 12:40:00 basically without the PM or AM. Here is what i have so far:

string StartTime = ((TextBox)TestDV.FindControl("txtBST")).Text.ToString();

thanks

Upvotes: 0

Views: 6897

Answers (3)

Mike Varosky
Mike Varosky

Reputation: 390

Since you are bringing it in as a string this is actually kind of easy.

string StartTime = ((TextBox)TestDV.FindControl("txtBST")).Text.ToString();
DateTime dt = new DateTime();
try { dt = Convert.ToDateTime(StartTime); } 
catch(FormatException) { dt = Convert.ToDateTime("12:00 AM"); }
StartTime = dt.ToString("HH:mm");

So you bring in your string, and convert it to a date. if the input is not a valid date, this will default it to 00:00. Either way, it gives you a string and a DateTime object to work with depending on what else you need to do. Both represent the same value, but the string will be in 24-Hour format.

Cheers!!

Upvotes: 3

D Stanley
D Stanley

Reputation: 152644

One option would be to parse into a DateTime and then back to a string:

string s = "12:40 PM";

DateTime dt = DateTime.Parse(s);

string s2 = dt.ToString("HH:mm:ss");  // 12:40:00

Be aware, however, that most operations work better with a DateTime versus a string representation of a DateTime.

Upvotes: 8

Jon Skeet
Jon Skeet

Reputation: 1503869

First you should parse it to a DateTime, then format it. It sounds like your input format is something like hh:mm tt and your output format is HH:mm:ss. So, you'd have:

string input = "12:40 PM"
DateTime dateTime = DateTime.ParseExact(input, "hh:mm tt",
                                        CultureInfo.InvariantCulture);
string output = dateTime.ToString("HH:mm:ss", CultureInfo.InvariantCulture);

Note that:

  • I've used DateTime.ParseExact which will throw an exception if the parsing fails; you may want to use DateTime.TryParseExact (it depends on your situation)
  • I've used the invariant culture for both operations here. I don't know whether or not that's correct for your scenario.
  • I've used hh:mm, but you might want h:mm... would you expect "1 PM" or "01 PM"?
  • You don't parse seconds, so that part will always be 0... is that okay?

Upvotes: 5

Related Questions