如何使用 CultureInfo 获取 12 小时或 24 小时时间(不带日期)

How do I use CultureInfo to get the 12-hour or 24-hour time (without the date)

我想使用 C# 以适当的文化格式格式化一天中的时间。

例如,如果当前文化是 en-US 我想显示 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,它具有文化敏感性(在法国它应该是空白的)。

如何在没有日期的情况下获取适合当前文化的时钟格式?

我没有看到任何其他选项来检查 CurrentCulture 信息并根据 that 以不同方式设置 timeOfDay 格式(因为您的字符串具有不同的格式)文化。

if (CultureInfo.CurrentCulture == new CultureInfo("en-US"))
{
    time = timeOfDay.ToString("h:mm tt", CultureInfo.CurrentCulture);
}

if (CultureInfo.CurrentCulture == new CultureInfo("fr-FR"))
{
    time = timeOfDay.ToString("HH:mm", CultureInfo.CurrentCulture);
}

这似乎有效:

string time = timeOfDay.ToString(CultureInfo.CurrentCulture.DateTimeFormat.ShortTimePattern, CultureInfo.CurrentCulture);

第二个参数可能也是不必要的。

如果您不需要明确说明,您可以使用 .ToShortTimeString() 并让系统确定格式。

https://msdn.microsoft.com/en-us/library/system.datetime.toshorttimestring(v=vs.110).aspx

The string returned by the ToShortTimeString method is culture-sensitive. It reflects the pattern defined by the current culture's DateTimeFormatInfo object. For example, for the en-US culture, the standard short time pattern is "h:mm tt"; for the de-DE culture, it is "HH:mm"; for the ja-JP culture, it is "H:mm". The specific format string on a particular computer can also be customized so that it differs from the standard short time format string.

重点是我的。


编辑以演示此用例:

//ToShortTimeString automatically uses current culture to show hour:minute
string time = timeOfDay.ToShortTimeString();