DateTime parameter with and without leading zeros
I have a TextBox where the user can enter a date. I only expect the following formats:
12.12.2017
12.02.2017
12.2.2017
02.12.2017
2.12.2017
02.02.2017
2.2.2017
So there may be a leading zero or not.
I am currently parsing a DateTime with the following code:
DateTime myDate = new DateTime();
bool success = DateTime.TryParseExact(TboDate.Text, "dd.MM.yyyy",
CultureInfo.CurrentUICulture, DateTimeStyles.None, out myDate);
Dates of the type 12.2.2017
cannot be successfully parsed with this code. But I don't want to check the string every time and parse it with the appropriate format d.M.yyyy, dd.M.yyyy, d.MM.yyyy
and so on. Is there an easier way to tell the method what leading zeros can be?
source to share
All of them can be parsed without problems with Parse
/ TryParse
fe with de-DE culture:
var dates = new[] { "12.12.2017", "12.02.2017", "12.2.2017", "02.12.2017", "2.12.2017", "02.02.2017", "2.2.2017" };
foreach (var dateStr in dates)
{
DateTime dt;
if (!DateTime.TryParse(dateStr, CultureInfo.CurrentUICulture, DateTimeStyles.None, out dt))
{
Console.WriteLine("not valid: " + dateStr);
}
}
But you can also use ParseExact
if you specify all allowed formats:
string[] allowedFormats = { "dd.MM.yyyy", "d.MM.yyyy", "dd.M.yyyy", "d.M.yyyy" };
foreach (var dateStr in dates)
{
DateTime dt;
if (!DateTime.TryParseExact(dateStr, allowedFormats, CultureInfo.CurrentUICulture, DateTimeStyles.None, out dt))
{
Console.WriteLine("not valid: " + dateStr);
}
}
Refresh
As Jon Skeet said, it is not necessary to specify multiple, this handles everything: "d.M.yyyy"
source to share