我想使用C#以适当的文化格式格式化一天中的某个时间。
例如,如果当前文化是美国英语,我想显示1:00 PM,如果当前文化是fr-FR,我想显示13:00。我只想要一天中的时间,我不需要日期。
//timeOfDay is a DateTime object.
//This will return the 12 hour clock regardless of culture:
time = timeOfDay.ToString("h:mm tt", CultureInfo.CurrentCulture);
//This will return the 24 hour clock regardless of culture
time = timeOfDay.ToString("H:mm tt", CultureInfo.CurrentCulture);
//This will return the correct clock for the culture, but the date will also be present
time = timeOfDay.ToString(CultureInfo.CurrentCulture);
请注意,“ tt”表示AM / PM,在文化上是敏感的(在法国,应该是空白)。
如何获取没有当前日期的适用于当前区域性的时钟格式?
如果不需要明确,则可以使用.ToShortTimeString()
并让系统确定格式。
https://msdn.microsoft.com/zh-CN/library/system.datetime.toshorttimestring(v=vs.110).aspx
ToShortTimeString方法返回的字符串是区域性敏感的。它反映了当前区域性的DateTimeFormatInfo对象定义的模式。例如,对于美国文化,标准的短时间模式是“ h:mm tt”;对于de-DE文化,它是“ HH:mm”;对于ja-JP文化,它是“ H:mm”。还可以自定义特定计算机上的特定格式字符串,以使其与标准的短时间格式字符串不同。
重点是我的。
编辑以演示此用例:
//ToShortTimeString automatically uses current culture to show hour:minute
string time = timeOfDay.ToShortTimeString();
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句