I want to check if a date has a correct format. There is many possibilities of correct dates like:
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?
Update:
Based on the answers so far, 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?
TryParse(String, DateTime)Converts the specified string representation of a date and time to its DateTime equivalent and returns a value that indicates whether the conversion succeeded.
The DateTime TryParse method converts the string representation of a date and time to a DateTime object and returns true if the conversion was successful and false if otherwise.
TryParse(String, Int32) Converts the string representation of a number to its 32-bit signed integer equivalent. A return value indicates whether the conversion succeeded.
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());
}
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With