Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Datetime.TryParse can't parse yyyy/MM/dd format

I am at the moment trying to convert a date given in the format as yyyy/MM/dd. To check if a valid Date is given.

if(!DateTime.TryParse(textBoxDatumVanStorting.Text, out Test2))

Is what im using at the moment but it always gives me a wrong date.

I have Looked in to using DateTime.TryParseExact. But cant seem to get this to work.

like image 353
Blasje Avatar asked Sep 21 '25 01:09

Blasje


1 Answers

Specifying a Format

Consider using the DateTime.TryParseExact() method which will allow you to explicitly define the format your string is in :

// This will attempt to parse your date in exactly the format provided
if(!DateTime.TryParseExact(textBoxDatumVanStorting.Text,"yyyy/MM/dd", null, DateTimeStyles.None, out Date2))
{
    // Your date is not valid, consider doing something
}

A Matter of Culture

In the above example, the third parameter being passed in represents the specific culture / format that you expect to use to parse the date. Using null will default to the current culture, but if you need to explicitly specify this, you can do so here as seen using the invariant culture :

Date output;
if(!DateTime.TryParseExact(input,"yyyy/MM/dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out output))  
{
     // Uh oh again...
}
like image 142
Rion Williams Avatar answered Sep 22 '25 15:09

Rion Williams