Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
627 views
in Technique[技术] by (71.8m points)

c# - Get just the hour of day from DateTime using either 12 or 24 hour format as defined by the current culture

.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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
// 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, @"[^hHts]", "");
        format = Regex.Replace(format, @"s+", " ").Trim();

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

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...