Get custom date and time format from standard format

In my script, I get a standard format such as "D", "f", "R" or others. This is the standard DateTime format, according to MSDN.

Given the current culture of the user, I would like to get a custom format for this standard format.

For example, say my user from France (fr-FR):

"d" = "dd / MM / yyyy"

"D" = "dddd d MMMM yyyy"

"F" = "dddd d MMMM yyyy HH: mm: ss"

+4
source share
5 answers

You need a version of this char format, but then you can do it like this:

 CultureInfo culture = //get your culture var patterns = culture.DateTimeFormat.GetAllDateTimePatterns(yourFormatChar); 
+7
source

Here some code gets the patterns:

 var c = new CultureInfo("fr-FR"); Console.WriteLine(c.DateTimeFormat.LongDatePattern); Console.WriteLine(c.DateTimeFormat.ShortDatePattern); Console.WriteLine(c.DateTimeFormat.FullDateTimePattern); 

The result of using the console application is

 dddd d MMMM yyyy dd/MM/yyyy dddd d MMMM yyyy HH:mm:ss 
+2
source
 DateTimeFormatInfo dtf = CultureInfo.CurrentCulture.DateTimeFormat; switch (standardFormat) { case "d": return dtf.ShortDatePattern; case "D": return dtf.LongDatePattern; case "F": return dtf.FullDateTimePattern; // add other standard formatters default: throw new ArgumentException("Say what?", "standardFormat"); } 

The standard formatter documentation says what properties you need to look for.

+2
source

Use the various DateTimeFormat properties of the current thread (or UI thread, whichever is appropriate):

 "d" = Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern "D" = Thread.CurrentThread.CurrentCulture.DateTimeFormat.LongDatePattern "F" = Thread.CurrentThread.CurrentCulture.DateTimeFormat.FullDateTimePattern 
+2
source

Some reflection may ensure that you get the same extended format strings that are used internally:

 string GetRealFormat(string format, DateTimeFormatInfo dtfi) { MethodInfo method = Type.GetType("System.DateTimeFormat") .GetMethod("GetRealFormat", BindingFlags.Static | BindingFlags.NonPublic); return method.Invoke(null, new object[] { format, dtfi }) as string; } 
 string format = GetRealFormat("d", DateTimeFormatInfo.CurrentInfo) // dd.MM.yyyy 
+1
source

Source: https://habr.com/ru/post/1495607/


All Articles