Reputation: 3663
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.
Upvotes: 3
Views: 1685
Reputation: 3663
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'.
public static string SimplifyDateFormat(DateTimeFormatInfo DTFI)
{
StringBuilder SB = new StringBuilder(DTFI.ShortDatePattern.ToLower());
SB.Replace("m y", "m/y").Replace(" 'г.'", "").Replace(" ", "").Replace("dd", "d")
.Replace("mm", "m").Replace("yyyy", "y").Replace("yy", "y");
if (SB[SB.Length - 1] == '.') SB.Remove(SB.Length - 1, 1);
return SB.ToString();
}
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.
Upvotes: 2
Reputation: 3743
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...
Upvotes: 0