Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if current culture/locale uses am/pm or 24-hour time?

Tags:

.net

time

I need to determine if the current culture/locale is set to use am/pm time or 24-hour time.

At first I thought I could do this:

bool time24Hour = Thread.CurrentThread.CurrentCulture.DateTimeFormat.AMDesignator == "";

But then I read the comments on the last answer on this thread Get just the hour of day from DateTime using either 12 or 24 hour format as defined by the current culture which seems to imply this won't work.

I guess I could format an arbitrary time, and then analyze the results, but surely there's a simplier way?

EDIT:

See also my comment below - I just want to determine which one of two pre-formatted constant strings containing lists of hours I should select, and hope to avoid a lot of unnecessary contortions - I just need a yes/no answer as to whether this is an am/pm culture or a 24-hour culture.

The program is a WinForms program, if that is of any help.

like image 645
RenniePet Avatar asked Sep 04 '11 23:09

RenniePet


2 Answers

Try checking if DateTimeFormat.ShortTimePattern contains H. If it does, the system is using 24-hour time

like image 72
dario_ramos Avatar answered Nov 01 '22 17:11

dario_ramos


Just a small addition if I may. Based on the answer by dario_ramos, I turned this into an extension method with a supporting unit test, which passes on my system (checking 378 cultures).

public static class DateTimeExtensions
{
    public static bool Is24Hrs(this CultureInfo cultureInfo)
    {
        return cultureInfo.DateTimeFormat.ShortTimePattern.Contains("H");
    }
}

[TestClass]
public class DateTimeExtensionTests
{
    [TestMethod]
    public void Unit_Can_Determine_If_Culture_Uses_24HrTime()
    {
        var cultures = CultureInfo.GetCultures(CultureTypes.AllCultures);
        foreach (var cultureInfo in cultures)
        {
            Thread.CurrentThread.CurrentCulture = cultureInfo;
            var datetime = new DateTime(2000, 1, 1, 23, 0, 0);
            var formatted = datetime.ToString("t");
            var is24Hrs = formatted.Contains("23");
            Assert.AreEqual(is24Hrs, cultureInfo.Is24Hrs());
        }
    }
}
like image 25
sammy34 Avatar answered Nov 01 '22 19:11

sammy34