I have a time that is 16:23:01. I tried using DateTime.ParseExact
, but it\'s not working.
Here is my code:
string Time = \"16:23:01\";
Date
"16:23:01" doesn't match the pattern of "hh:mm:ss tt" - it doesn't have an am/pm designator, and 16 clearly isn't in a 12-hour clock. You're specifying that format in the parsing part, so you need to match the format of the existing data. You want:
DateTime dateTime = DateTime.ParseExact(time, "HH:mm:ss",
CultureInfo.InvariantCulture);
(Note the invariant culture, not the current culture - assuming your input genuinely always uses colons.)
If you want to format it to hh:mm:ss tt
, then you need to put that part in the ToString
call:
lblClock.Text = date.ToString("hh:mm:ss tt", CultureInfo.CurrentCulture);
Or better yet (IMO) use "whatever the long time pattern is for the culture":
lblClock.Text = date.ToString("T", CultureInfo.CurrentCulture);
Also note that hh
is unusual; typically you don't want to 0-left-pad the number for numbers less than 10.
(Also consider using my Noda Time API, which has a LocalTime
type - a more appropriate match for just a "time of day".)