如何获取已解析字符串的格式
DateTime.Parse 接受一个字符串并返回等效的 DateTime。
有没有办法获取解析器使用的格式?
例如,7/19/2011 将返回 M/dd/yyyy,而 19-7-2011 将返回 dd-M-yyyy。
如果 DateTime.TryParseExact 也返回正在使用的格式,那么它对我有用。
DateTime.Parse takes a string and returned the equivalent DateTime.
Is there a way to get the format being used by the parser?
For example, 7/19/2011 would return M/dd/yyyy while 19-7-2011 would return dd-M-yyyy.
DateTime.TryParseExact would work for me if it also returned the format being used.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是不可能的,因为
DateTime
格式和特定输出之间的映射不是同构的(每个输出没有到单一格式的反向映射) - 仅考虑 11-07-2011 的情况 -这是 dd-MM-yyyy 还是 MM-dd-yyyy?This is not possible because the mapping between a
DateTime
format and a particular output is not isomorphic (there is no inverse mapping to a single format for each output) - consider just the case 11-07-2011 - is this dd-MM-yyyy or MM-dd-yyyy?请参阅http://msdn.microsoft.com/en-us/library/1k1skd40。 aspx 特别是备注部分。
获取所需格式的最佳方法是阅读文档。
See http://msdn.microsoft.com/en-us/library/1k1skd40.aspx Specifically the Remarks section.
The best way to get the formats that it looks for is to read the docs.
DateTime.Parse
使用当前线程的当前区域性。Thread.CurrentThread.CurrentCulture.DateTimeFormat
将为您提供DateTimeFormatInfo
的只读实例,您可以使用它来检查格式。The property
ShortDatePattern
is the one you are looking for.This addresses your question regarding the format being used by the parser but there is no way to get the format after the fact.
DateTime.Parse
uses the current culture of the current thread.Thread.CurrentThread.CurrentCulture.DateTimeFormat
will give you a readonly instance ofDateTimeFormatInfo
that you can use to inspect the format.The property
ShortDatePattern
is the one you are looking for.This addresses your question regarding the format being used by the parser but there is no way to get the format after the fact.
循环遍历一次将一个格式传递给 DateTime.TryParseExact 的格式列表。
当您最终获得真实值时,您就确切地知道.Net 将使用哪种格式来解析它。
Loop through a list of formats that you pass one at a time to DateTime.TryParseExact.
When you finally get a true value then you know exactly which format .Net would use to parse it.