简体   繁体   English

时间格式

[英]c# Time formatting

I have a time field as such: 06:30 PM. 我有一个这样的时间字段:06:30 PM。 What formatting do I need so that it shows up as 6:30 PM. 我需要什么格式才能显示为6:30 PM。 I tried: 我试过了:

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

but still getting 06:30 PM 但仍然下午06:30

Well, t is the standard format string for "short time pattern" - so it's being formatted according to the current culture's rules. 好吧, t是“短时间模式”的标准格式字符串 -因此,它是根据当前区域性规则进行格式化的。 For me, it would show "18:30" because that's the appropriate format for the UK. 对我来说,它将显示“ 18:30”,因为这是适用于英国的格式。

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 可以坚持.NET知道规则,或者您可以使用自定义的日期和时间格式字符串来强制特定的格式,如

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.) (请注意,这基本上等效于string.Format("{0:h:mm tt}", date)但更易于阅读-我建议仅在真正格式化多个值时才使用复合格式。 )

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. 通常,这并不是一个好主意-它表明您比Windows / .NET了解更多有关文化规则的知识,而事实并非如此。 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: 也可以看看:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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