tags:

views:

484

answers:

4

I want to check if a date has a correct format. There is many possibilities of correct dates like:

  • 02.08.2010
  • 2.8.2010
  • 02.8.2010 02.08
  • 02.August
  • ...

I can test each on with code like this:

if (DateTime.TryParse(DateTime.ParseExact(date, "dd.M.", 
                              new CultureInfo("sl-SI")).ToString(), out dt))

But then i can have 40 if statements. Is it possible to check all dates with one if statement or one loop?

+5  A: 

Yes ParseExact can take a list of formats to check against.

var formats = new[] { "M.d.yyyy", "dd.MM.yyyy" };
var dateValue = DateTime.ParseExact(
    dateString, formats, new CultureInfo("sl-SI"), DateTimeStyles.None);
Darin Dimitrov
+1  A: 

You can use something like the following, but be aware that more than one format might be able to parse the same date. For example 10/11/12 can be parsed as yy/MM/dd or MM/dd/yy, which are both valid US date formats. MM/dd/yy is more common, so it appears first in the list and is the one returned by the code below (if you use it with a US culture instead of the culture in the example).

string testValue = "10.11.12";

DateTime result;
CultureInfo ci = CultureInfo.GetCultureInfo("sl-SI");
string[] fmts = ci.DateTimeFormat.GetAllDateTimePatterns();
Console.WriteLine(String.Join("\r\n", fmts));
if (DateTime.TryParseExact(testValue, fmts, ci,
   DateTimeStyles.AssumeLocal, out result))
{
   Console.WriteLine(result.ToLongDateString());
}
BlueMonkMN
In the part of the world where I live, humans would parse it as "dd.mm.yy". Taking that into account, the whole question makes little sense, because it's prone to misinterprations.
ammoQ
A: 

Thy boath for answer. Now i am testing this code, but i have one more problem. What if i have just 9.2 not 9.2.2010 then this code will not work:

CultureInfo ci = CultureInfo.GetCultureInfo("sl-SI");
        string[] fmts = ci.DateTimeFormat.GetAllDateTimePatterns();

        if (DateTime.TryParseExact(date, fmts, ci, DateTimeStyles.AssumeLocal, out dt))
        {
            DateTime = Convert.ToDateTime(date);
            Check = true;
        }

Must i manually add this times or what can i do?

senzacionale
Edit your question, don't add this as an answer. And follow Darin's advice, if you want to use formats that aren't already in the pattern list of the `CultureInfo`, then you need to add your own.
Aaronaught
thx for answer. I fixed now. Thx all again.
senzacionale
A: 

thx for answer. I fixed now. Thx all again.

senzacionale
If one of the answer solved your problem, then accept it. Otherwise, you can answer your own question, but then please describe your own solution. Saying thanks is nice, but not an answer :)
ewernli