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

标签 c# .net culture datetime-format

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

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

谢谢!

最佳答案

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

关于c# - 使用当前区域性定义的 12 或 24 小时格式从 DateTime 获取一天中的小时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3015040/

相关文章:

SQL 服务器 .Net CLR 文化

c# - Azure 文化特定的月/日格式与 localhost 不同

c# - 如何使用 System.Security.Cryptography 生成随机 int 值

c# - 如何查看一个字符串是否包含另一个带引号的字符串?

c# - 我们可以在 .NET 中安全地执行核心关联吗?

c# - 将值从 View 传递到 Controller,我缺少什么?

c# - 在 C# 2008 中从数据库中检索记录

javascript - 通过 document.location 在 javascript 中将文件路径作为字符串传递

.net - MVVM 基础与 MVVM 工具包

algorithm - 蒙古语名字的处理