Apollo
Apollo

Reputation: 2070

Convert string to Time

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"; 
DateTime date = DateTime.ParseExact(Time, "hh:mm:ss tt", System.Globalization.CultureInfo.CurrentCulture);

lblClock.Text = date.ToString();

I want it to show in the label as 04:23:01 PM.

Upvotes: 54

Views: 230795

Answers (5)

Electrionics
Electrionics

Reputation: 6772

Since .NET 6 you can use TimeOnly struct:

var time = TimeOnly.Parse("16:23:01");
var str = time.ToString("R"); // 16:23:01

Full documentation can be found here.

Upvotes: 0

Aleks
Aleks

Reputation: 355

The accepted solution doesn't cover edge cases. I found the way to do this with 4KB script. Handle your input and convert a data.

Examples:

00:00:00 -> 00:00:00
12:01 -> 12:01:00
12 -> 12:00:00
25 -> 00:00:00
12:60:60 -> 12:00:00
1dg46 -> 14:06

You got the idea... Check it https://github.com/alekspetrov/time-input-js

Upvotes: -2

user2704193
user2704193

Reputation:

This gives you the needed results:

string time = "16:23:01";
var result = Convert.ToDateTime(time);
string test = result.ToString("hh:mm:ss tt", CultureInfo.CurrentCulture);
//This gives you "04:23:01 PM"  string

You could also use CultureInfo.CreateSpecificCulture("en-US") as not all cultures will display AM/PM.

Upvotes: 6

Jon Skeet
Jon Skeet

Reputation: 1499800

"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".)

Upvotes: 100

SteveB
SteveB

Reputation: 1514

string Time = "16:23:01";
DateTime date = DateTime.Parse(Time, System.Globalization.CultureInfo.CurrentCulture);

string t = date.ToString("HH:mm:ss tt");

Upvotes: 13

Related Questions