I'm currently allowing users to set their preferred DateTime format using full patterns like so:
var formats = System.Globalization.CultureInfo.CurrentUICulture.DateTimeFormat.GetAllDateTimePatterns('f').ToList();
formats.AddRange(System.Globalization.CultureInfo.CurrentUICulture.DateTimeFormat.GetAllDateTimePatterns('F'));
formats.AddRange(System.Globalization.CultureInfo.CurrentUICulture.DateTimeFormat.GetAllDateTimePatterns('g'));
formats.AddRange(System.Globalization.CultureInfo.CurrentUICulture.DateTimeFormat.GetAllDateTimePatterns('G'));
This produces full pattern strings like this:
dddd, MMMM d, yyyy h:mm tt
dddd, MMMM d, yyyy hh:mm tt
dddd, MMMM d, yyyy H:mm
dddd, MMMM d, yyyy HH:mm
MMMM d, yyyy h:mm tt
dddd, d MMMM, yyyy h:mm:ss tt
M/d/yyyy h:mm tt
There are certain places in the UI where we don't want to show the Time because its irrelevant in context.
Is there a culture aware BCL class that allows me to extract just the Date pattern from a string?
Example api:
var datePattern = System.Globalization.CultureInfo.CurrentUICulture.DateTimeFormat.GetDatePattern("M/d/yyyy h:mm tt");
Which would result in datePattern being set to:
M/d/yyyy
Update
Based on @SteveWellens comment I realized that Date/Time patterns are not in themselves culture variant which is what was throwing me off. In other words the "h" that represents a placeholder for the hour is always "h" no matter what culture the end user is in. I created a dead simple extension method to get what I wanted. (wish this didn't have to be a string extension though because it clutters intellisense)
public static string GetDatePattern(this string pattern)
{
// set a default pattern if none is specified
if (string.IsNullOrWhiteSpace(pattern))
pattern = System.Globalization.CultureInfo.CurrentUICulture.DateTimeFormat.FullDateTimePattern;
var start = pattern.IndexOf("h", StringComparison.InvariantCultureIgnoreCase);
// cannot find the hour placeholder
if (start < 0)
return pattern;
return pattern.Substring(0, start -1);
}
NOTES: I double checked all the cultures (CultureTypes.AllCultures) and none of the standard date and time patterns start with a time pattern for any of them so this is safe logic to use for standard date and time patterns. Custom patterns are a whole other story.
FYI, the longest standard date and time pattern for any culture is 48 in case you are saving this to a database.