Here's how to parse dates and times using built-in .Net libraries:
static void Main(){ string strTime = "01:00:10AM"; DateTime time; if (DateTime.TryParseExact(strTime, "hh:mm:sstt", null, System.Globalization.DateTimeStyles.None, out time)) { Console.WriteLine("Parsed \"{0}\" as {1:HH\\:mm\\:ss}", strTime, time); } else { Console.WriteLine("Could not parse \"{0}\" as a DateTime", strTime); } Console.ReadLine();}
Some points to note:
- I'm not reinventing the wheel. The .Net DateTime library is the best way to handle points in time. (Use TimeSpan for duration)
- I'm using custom DateTime format strings for both parsing the string and displaying the parsed DateTime result.
- I'm using the
TryParse
pattern the .Net supplies for converting strings to various built-in types: e.g., int.TryParse, double.TryParse, etc. - In the output, I want to display the parsed time as
HH:mm:ss
(note that capital H is 24 hour time and lowercase h is 12 hour time). I have to escape the colons in there because of how string.Format works. You escape colons using backslashes like thisHH\:mm\:ss
. The problem is that you then have to escape the backslashes (or use verbatim strings). You do that with an extra backslash like thisHH\\:mm\\:ss