I get a time format string passed to me in a string. It could be a standard string like "t", but could be a custom one (containing "HH", etc). How can I find out, that if displayed it'll be a 12-hour or 24-hour format? (depending on culture and everything...)
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
The easiest way is to try a date that you can then examine for a given number in the string, that you'd only expect that way. E.g. whether
2000-01-01T19:00:00Z
resulted in a string containing a7
or a9
or both.To be certain in the face of even strange strings like
"'This valid string will mess you up 79'"
, then you need to examine the string, after obtaining the full version for the given culture info if needed.The following would also make sense as an extension method on
CultureInfo
orDateTimeFormatInfo
.In practice, you can simplify by putting those standard formats that normally include only date-info in the group that returns
None
immediately, but I decided to catch even strangeness there:Step 1: If necessary, turn a standard format string into the selected culture's equivalent custom format string. This uses reflected logic to mimic
DateTime.ToString
.Step 2: parse the string to see if it contains 12- or 24- hour specifiers. This is an unfortunate mix of using reflected logic to mimic
DateTime.ToString
as far as possible and custom logic where not possible, but it seems to work OK.This relies on the following two
MethodInfo
s gained by reflection:The first handles turning a single-character standard format specifier into a multiple-character custom format specifier for a given culture. The second handles quoted literals inside a custom format specifier.
You could format a known date using the string, one which you know will only contain a particular value if it's using 24 hour time: