简体   繁体   中英

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

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, eg

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.

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

See also:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM