使用当前文化定义的12或24小时格式从DateTime获取一天中的小时

时间:2010-06-10 13:55:59

标签: c# .net culture datetime-format

.Net具有针对DateTime的内置ToShortTimeString()函数,该函数使用CultureInfo.CurrentCulture.DateTimeFormat.ShortTimePattern格式。它会为en-US返回类似的内容:“下午5:00”。对于像de-DE这样的24小​​时文化,它将返回“17:00”。

我想要的是一种方法,只需返回适用于每种文化的小时(上述案例中的“下午5点”和“17”)。什么是最好/最干净的方法?

谢谢!

7 个答案:

答案 0 :(得分:6)

// displays "15" because my current culture is en-GB
Console.WriteLine(DateTime.Now.ToHourString());

// displays "3 pm"
Console.WriteLine(DateTime.Now.ToHourString(new CultureInfo("en-US")));

// displays "15"
Console.WriteLine(DateTime.Now.ToHourString(new CultureInfo("de-DE")));

// ...

public static class DateTimeExtensions
{
    public static string ToHourString(this DateTime dt)
    {
        return dt.ToHourString(null);
    }

    public static string ToHourString(this DateTime dt, IFormatProvider provider)
    {
        DateTimeFormatInfo dtfi = DateTimeFormatInfo.GetInstance(provider);

        string format = Regex.Replace(dtfi.ShortTimePattern, @"[^hHt\s]", "");
        format = Regex.Replace(format, @"\s+", " ").Trim();

        if (format.Length == 0)
            return "";

        if (format.Length == 1)
            format = '%' + format;

        return dt.ToString(format, dtfi);
    }
}

答案 1 :(得分:4)

我会检查CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern是否包含“h”,“hh”,“H”,“HH”,“t”或“tt”,以及以什么顺序,然后构建你的拥有自定义格式字符串。

e.g。

  • en-US:将“h:mm tt”映射到“h tt”
  • ja-JP:将“H:mm”映射到“H”
  • fr-FR:将“HH:mm”映射到“HH”

然后使用.ToString(),传入你构建的字符串。

示例代码 - 这基本上删除了不是t,T,h,H和多个空格的所有内容。但是,如下所述,只有一串“H”可能会失败......

string full = System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.ShortTimePattern;
string sh = String.Empty;
for (int k = 0; k < full.Length; k++)
{
    char i = full[k];
    if (i == 'h' || i == 'H' || i == 't' || i == 'T' || (i == ' ' && (sh.Length == 0 || sh[sh.Length - 1] != ' ')))
    {
        sh = sh + i;
    }
}
if (sh.Length == 1)
{
  sh = sh + ' ';
  string rtnVal = DateTime.Now.ToString(sh);
  return rtnVal.Substring(0, rtnVal.Length - 1);
{
else
{
    return DateTime.Now.ToString(sh);
}

答案 2 :(得分:2)

使用此:

bool use2fHour =
    CultureInfo
        .CurrentCulture
        .DateTimeFormat
        .ShortTimePattern.Contains("H");

答案 3 :(得分:0)

您可以使用DateTime.ToString()并提供tyou想要的格式作为参数。

答案 4 :(得分:0)

呃,我不想有兴趣,但现在我是!这里的代码尊重所有文化,使AM / PM指示符处于正确的位置,并识别24小时格式,所有这些都取决于文化。

基本上,这个静态扩展方法被重载以获取当前文化(没有参数)或指定的文化。

DateTime.Now.ToTimeString()
DateTime.Now.ToTimeString(someCultureInfo)

代码如下,包括示例程序:

    public static class DateTimeStaticExtensions
    {
        private static int GetDesignatorIndex(CultureInfo info)
        {
            if (info.DateTimeFormat
                .ShortTimePattern.StartsWith("tt"))
            {
                return 0;
            }
            else if (info.DateTimeFormat
                .ShortTimePattern.EndsWith("tt"))
            {
                return 1;
            }
            else
            {
                return -1;
            }
        }

        private static string GetFormattedString(int hour, 
            CultureInfo info)
        {
            string designator = (hour > 12 ? 
                info.DateTimeFormat.PMDesignator : 
                info.DateTimeFormat.AMDesignator);

            if (designator != "")
            {
                switch (GetDesignatorIndex(info))
                {
                    case 0:
                        return string.Format("{0} {1}",
                            designator, 
                            (hour > 12 ? 
                                (hour - 12).ToString() : 
                                hour.ToString()));
                    case 1:
                        return string.Format("{0} {1}",
                            (hour > 12 ? 
                                (hour - 12).ToString() :
                                hour.ToString()), 
                            designator);
                    default:
                        return hour.ToString();
                }
            }
            else
            {
                return hour.ToString();
            }
        }

        public static string ToTimeString(this DateTime target, 
            CultureInfo info)
        {
            return GetFormattedString(target.Hour, info);
        }

        public static string ToTimeString(this DateTime target)
        {
            return GetFormattedString(target.Hour, 
                CultureInfo.CurrentCulture);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            var dt = new DateTime(2010, 6, 10, 6, 0, 0, 0);

            CultureInfo[] cultures = 
                CultureInfo.GetCultures(CultureTypes.SpecificCultures);
            foreach (CultureInfo culture in cultures)
            {
                Console.WriteLine(
                    "{0}: {1} ({2}, {3}) [Sample AM: {4} / Sample PM: {5}",
                    culture.Name, culture.DateTimeFormat.ShortTimePattern,
                    (culture.DateTimeFormat.AMDesignator == "" ? 
                        "[No AM]": 
                        culture.DateTimeFormat.AMDesignator),
                    (culture.DateTimeFormat.PMDesignator == "" ? 
                        "[No PM]": 
                        culture.DateTimeFormat.PMDesignator),
                    dt.ToTimeString(culture),  // AM sample
                    dt.AddHours(12).ToTimeString(culture) // PM sample
                    );
            }

            // pause program execution to review results...
            Console.WriteLine("Press enter to exit");
            Console.ReadLine();
        }
    }

答案 5 :(得分:-1)

var culture = CultureInfo.CurrentCulture;
bool uses24HourClock = string.IsNullOrEmpty(culture.DateTimeFormat.AMDesignator);

var dt = DateTime.Now;
string formatString = uses24HourClock ? "HH" : "h tt";
Console.WriteLine(dt.ToString(formatString, culture));

Sam的编辑:

以下代码证明这不起作用。

var date = new DateTime(2010, 1, 1, 16, 0, 0);

foreach (CultureInfo cultureInfo in CultureInfo.GetCultures(CultureTypes.InstalledWin32Cultures))
{
    bool amMethod = String.IsNullOrEmpty(cultureInfo.DateTimeFormat.AMDesignator);
    bool formatMethod = cultureInfo.DateTimeFormat.ShortTimePattern.Contains("H");

    if (amMethod != formatMethod)
    {
        Console.WriteLine("**** {0} AM: {1} Format: {2} Designator: {3}  Time: {4}",
                          cultureInfo.Name,
                          amMethod,
                          formatMethod,
                          cultureInfo.DateTimeFormat.AMDesignator,
                          date.ToString("t", cultureInfo.DateTimeFormat));
    }
}

答案 6 :(得分:-1)

尝试使用DateTime.Hour属性。