计算用于日期时间格式化的字符串格式
我有一个代表 DataTime 值的字符串,我想了解创建该字符串时使用的字符串格式。
例如
- 鉴于“2010 年 1 月 27 日星期三”,我期望“dddd dd MMM yyyy”
- 给定“2010 01 27”,我期望“yyyy MM dd”
假设日期接近 DateTime.Now 并且与 CurrentCulture 相关。鉴于我们有 en-GB 文化
- 鉴于“01 01 2010”我期望“dd MM yyyy”
有没有简单的方法可以做到这一点?
I have a string which represents a DataTime value, and I want to workout what string format was used to create the string.
For example
- Given "Wednesday 27 Jan 2010" I expect "dddd dd MMM yyyy"
- Given "2010 01 27" I expect "yyyy MM dd"
Assume that the date is close to DateTime.Now and relates to the CurrentCulture. So given that we have en-GB culture
- Given "01 01 2010" I expect "dd MM yyyy"
Is there a simple way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
最简单的方法是查看日期时间格式字符串的参考并解决它们。
您可以使用反射来获取此信息,或使用反汇编程序(例如 ILDASM) 查找程序集中使用的所有字符串并猜测哪些是日期时间格式字符串。
如果反汇编,您可以搜索星期几以及以 dddd 开头的字符串,这应该告诉您原始的构造方式。
The simplest thing to do is look at the reference for datetime formatting strings and working them out.
You may be able to use reflection in order to get this, or use disassembler (such as ILDASM) to find all the strings used in an assembly and guess at which ones are datetime formatting string.
If disassmbling, you can search for the days of the week and for a string starting with
dddd
, which should tell you how the original was constructed.您可以按空格分割以获得字符串数组
然后您可以根据已知值测试数组中的元素以尝试猜测格式
,例如如果您搜索“星期三”,如果您发现它假设“dddd”,
如果四位数字假设 yyyy
天和月可能是一个问题,您可以测试 > > 12 天,但这很糟糕,
也许您可以使用空格分割然后在原始数据上使用 DateTime.Parse 来推断格式,并针对解析日期的格式化(使用推断格式)版本进行测试是否相等
you could split on whitespace to get an array of strings
then you could test the elements in the array against known values to try to guess the format
e.g. if you search for "Wednesday" if you find it assume "dddd"
if a four digit number assume yyyy
days and months could be a problem, you could test for > 12 for the days but that's pretty bad
maybe you could infer the format using whitespace split then DateTime.Parse on the orignal and test against a formatted (using the infered format) version of the parsed date for equality