Nate Pet
Nate Pet

Reputation: 46222

c# Time formatting

I have a time field as such: 06:30 PM. What formatting do I need so that it shows up as 6:30 PM. I tried:

     String.Format("{0:t}", data.PgTime) 

but still getting 06:30 PM

Upvotes: 0

Views: 555

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1499800

Well, t is the standard format string for "short time pattern" - so it's being formatted according to the current culture's rules. For me, it would show "18:30" because that's the appropriate format for the UK.

You can either stick to the rules .NET knows about, or you can use a custom date and time format string to force a specific format, e.g.

string text = date.ToString("h:mm tt");

(Note that this is basically equivalent to string.Format("{0:h:mm tt}", date) but considerably simpler to read - I'd suggest only using composite formatting when you're really formatting more than one value.)

Usually that would not be a good idea though - it suggests that you know more about cultural rules than Windows / .NET, which is unlikely to really be the case. I'm sure you know more about how you personally like to format dates and times, but that's not the same as it being the standardized convention for your culture.

Upvotes: 5

String.Format("{0:h:mm tt}", data.PgTime)

See also:

Upvotes: 2

Related Questions