Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse DateTime with and without leading zeros

I have a TextBox in which the user can type a date. I only expect 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 can be a leading zero or not.

I am currently parsing the DateTime with following code:

DateTime myDate = new DateTime();
bool success = DateTime.TryParseExact(TboDate.Text, "dd.MM.yyyy", 
                   CultureInfo.CurrentUICulture, DateTimeStyles.None, out myDate);

Dates like 12.2.2017 can not be parsed successfully with that code. But I don't want to check the string everytime and parse it then with the matching format d.M.yyyy, dd.M.yyyy, d.MM.yyyy and so on. Is there an easier way to tell the method, that there can be leading zeros?

like image 358
L3n95 Avatar asked Apr 10 '17 08:04

L3n95


1 Answers

They could all be parsed without a problem with Parse/TryParse f.e. 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 could 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);
    }
}

Update

As Jon Skeet has mentioned it's not necessary to specify multiple, this handles all: "d.M.yyyy"

like image 124
Tim Schmelter Avatar answered Nov 17 '22 18:11

Tim Schmelter