.net Culture specific 12/24 hour formatting

13,865

Solution 1

I'd probably do something like this:

        var culture = CultureInfo.CurrentCulture;
        var pattern = culture.DateTimeFormat.LongTimePattern; // or pick which one you want to use;
        var newPattern = pattern.Replace("h", "H").Replace("t", "");
        DateTime.Now.ToString(newPattern); // or use whatever DateTime you want to use

From the chat:

Here is a list of all cultures' long time pattern strings, and how they would be modified:

Old: hh:mm:ss tt New: HH:mm:ss 
Old: HH:mm:ss 'ч.' New: HH:mm:ss 'ч.'
Old: HH:mm:ss New: HH:mm:ss
Old: H:mm:ss New: H:mm:ss
Old: h:mm:ss tt New: H:mm:ss 
Old: tt h:mm:ss New:  H:mm:ss
Old: h:mm:ss.tt New: H:mm:ss.
Old: HH.mm.ss New: HH.mm.ss
Old: tt hh:mm:ss New:  HH:mm:ss

Solution 2

You can use custom date/time format strings - e.g.:

For 12 hour rendering:

DateTime.Now.ToString("hh:mm:ss tt");

for 24-hour rendering:

DateTime.Now.ToString("HH:mm:ss");

To combine with a date format from the current culture, you can use one of:

DateTime.Now.ToString("d") + DateTime.Now.ToString(" hh:mm:ss tt");
DateTime.Now.ToString(CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern + 
                                      " hh:mm:ss tt");

Solution 3

That depends on what cultures you're talking about. Some cultures don't accept 24 hour time, and others don't accept AM/PM. The safest choice is probably InvariantCulture.

Share:
13,865
TravisWhidden
Author by

TravisWhidden

Updated on June 21, 2022

Comments

  • TravisWhidden
    TravisWhidden almost 2 years

    Is there a way to keep the culture specific date time formatting but force 12/24 hour rendering? I know I can do a lot with the actual date/time format string like HH:mm:ss and hh:mm:ss but I would like to honor the current user culture formatting (i.e. mm/dd/yyyy or yyyy/mm/dd, etc), just force 12/24 hour time rendering.