Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.net Culture specific 12/24 hour formatting

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.

like image 946
TravisWhidden Avatar asked Nov 10 '11 21:11

TravisWhidden


People also ask

How to convert 12 Hrs to 24 Hrs in c#?

Firstly, set the 12 hr format date. DateTime d = DateTime. Parse("05:00 PM"); Now let us convert it into 24-hr format.

How to get time in 24 hour format c#?

DateTime date = DateTime. ParseExact(strDate, "dd/MM/YYYY HH:mm:ss", CultureInfo. InvariantCulture);

What is CultureInfo in DateTime?

If UseUserOverride is true and the specified culture matches the current culture of Windows, the CultureInfo uses those overrides, including user settings for the properties of the DateTimeFormatInfo instance returned by the DateTimeFormat property, and the properties of the NumberFormatInfo instance returned by the ...

What is 24 hour format DateTime?

The pattern dd/MM/yyyy hh:mm:ss aa is used for the 12 hour format and the pattern MM-dd-yyyy HH:mm:ss is used for the 24 hour format.


1 Answers

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
like image 186
McKay Avatar answered Sep 19 '22 22:09

McKay