C# - 解析不同格式的部分日期
为了在搜索方法中使用,我想解析不同格式的部分日期。 我想让用户能够搜索日和月或月和年或者日和月和年。
但更成问题的是,我想根据用户所在的国家/地区以所有可能的日期格式执行此操作。这是一个 ASP.NET 页面,我可以使用 CultureInfo,因此也可以使用 CultureInfo.DateTimeFormat。
你知道如何做这样的事情吗?我认为如果英国人可以搜索 16/05,而美国人可以输入 05/16,或者德国人可以使用 16.05 来查找 5 月 16 日的结果,那就太好了。
我认为可以使用 DateTimeFormat.ShortDatePattern。但我怎样才能用它来获取日、月和年呢?
我想到的用途是
public void GetDateParts(string SearchStr, out int? day, out int? month, out int? year)
感谢任何可以帮助我的人。
For use in a search method i would like to parse partial dates in different formats.
I want to enable the user to search for day and month or month and year or also day and month and year.
But the more problematic thing is that i want do this in all possible date formats depending on the country, the user is in. It's a ASP.NET page and i can use the CultureInfo and therefore also the CultureInfo.DateTimeFormat.
Do you have any idea, how to do something like that? I think it would be great that a british person could search 16/05, while an american could enter 05/16 or a german could use 16.05 to find a result from the 16th of may.
I think it could be possible to use the DateTimeFormat.ShortDatePattern. But how could i use it to get day, month and year out of them?
I think of a use like
public void GetDateParts(string SearchStr, out int? day, out int? month, out int? year)
Thanks to anyone who can help me with this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
就像你们大多数人提到的那样,我想我会选择带有日期选择器或下拉菜单的方法。
但对于那些对另一种解决方案感兴趣的人:
我思考了不同的格式一段时间,发现它们在大多数情况下非常相似。所以我编写了一个方法,它返回更常用模式的最佳匹配版本。所以'dmy' -> 'dmy' 或 'd/m y' -> “日/月/年”。
这将可能的格式数量从 26 种减少到这 8 种:
这些只是通过正则表达式解析的 3 种不同格式 if您使用 [/.-] 作为分隔符。
PS 仍然无法解决部分日期的问题。但可以搜索所有文化的完整日期。
Like most of you mentioned, i think i will choose a method with a datepicker or dropdowns.
But for those who are interested in another solution:
I thought about the different formats for a while and found that they are very similar in most cases. So i wrote a method that returns the best matching version of more often used patterns. So 'd.m.y.' -> 'd.m.y' or 'd/m y' -> 'd/m/y'.
This reduces the amount of possible formats from 26 to these 8:
These are only 3 different formats for parsing via regex if you use [/.-] for the seperators.
P.S. Still doesn't fix the problem with partial dates. But search with full date for all cultures is possible.
您可以定义多种输入格式,然后在表单中强制使用其中一种格式(基于有关用户的信息)。例如:
“输入日期(DD-MM):_ - _”表示英国
“输入日期(MM-DD):_ - _”表示美国
等。 。
You can define a number of input formats and then impose one of them(based on info about the user) in your forms. Something like:
"Enter date(DD-MM):_ - _" for british
"Enter date(MM-DD):_ - _" for american
etc...