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

发布于 2024-09-04 22:24:50 字数 267 浏览 3 评论 0原文

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

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

谢谢!

.Net has the built in ToShortTimeString() function for DateTime that uses the CultureInfo.CurrentCulture.DateTimeFormat.ShortTimePattern format. It returns something like this for en-US: "5:00 pm". For a 24 hour culture such as de-DE it would return "17:00".

What I want is a way to just return just the hour (So "5 pm" and "17" in the cases above) that works with every culture. What's the best/cleanest way to do this?

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

ˇ宁静的妩媚 2024-09-11 22:24:51

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

you may use DateTime.ToString() and provide format tyou want as an argument.

大海や 2024-09-11 22:24:51

呃,我本来不想感兴趣,但现在我感兴趣了!下面的代码尊重所有文化,将 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();
        }
    }

Ugh, I didn't want to be interested but now I am! Here's the code which respects all cultures and renders the AM/PM designators in the correct position, as well as recognizing 24-hour format, all depending on the culture.

Basically, this static extension method is overloaded to take the current culture (no parameters) or a specified culture.

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

Code is below, includes sample program:

    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();
        }
    }
请止步禁区 2024-09-11 22:24:51
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));
    }
}
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's edit:

Here's code to prove this doesn't work.

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));
    }
}
誰ツ都不明白 2024-09-11 22:24:51

尝试使用 DateTime.Hour 属性。

Try using DateTime.Hour property.

最舍不得你 2024-09-11 22:24:50
// 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);
    }
}
// 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);
    }
}
夜唯美灬不弃 2024-09-11 22:24:50

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

例如

  • 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);
}

I would check to see whether CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern contains "h", "hh", "H", "HH", "t" or "tt", and in what order, and then build your own custom format string from those.

e.g.

  • en-US: map "h:mm tt" to "h tt"
  • ja-JP: map "H:mm" to "H"
  • fr-FR: map "HH:mm" to "HH"

Then use .ToString(), passing in the string you built.

Example code - this basically strips out everything that's not t, T, h, H, and multiple spaces. But, as pointed out below, just a string of "H" could fail...

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);
}
怪我闹别瞎闹 2024-09-11 22:24:50

使用这个:

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

Use this:

bool use2fHour =
    CultureInfo
        .CurrentCulture
        .DateTimeFormat
        .ShortTimePattern.Contains("H");
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文