3

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.

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Blasje
  • 37
  • 1
  • 1
  • 4
  • 2
    Possible duplicate of [DateTime parsing of custom date format in .NET](http://stackoverflow.com/questions/2560540/datetime-parsing-of-custom-date-format-in-net) – Xavier J Jun 02 '16 at 17:27
  • What is _wrong date_ exactly? What is your `textBoxDatumVanStorting.Text` and your `CurrentCulture`? – Soner Gönül Jun 02 '16 at 17:27
  • Well the Format im using is yyyy/MM/dd. textBoxDatumVanStorting.Text contains 1994/09/27 as date. But Tryparse is unable to parse the format im using . – Blasje Jun 02 '16 at 17:29

2 Answers2

15

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...
}
Rion Williams
  • 74,820
  • 37
  • 200
  • 327
  • Thanks this worked. Only had to change DateTimeStyles.None to System.Globalization.DateTimeStyles.None – Blasje Jun 02 '16 at 17:42
  • @Blasje - You can add `using System.Globalization` at the top of your file so you won't need to type so much code. – Chris Dunaway Jun 02 '16 at 18:15
0

If DateTime.TryParse can't parse your string, that means this yyyy/MM/dd format is not a standard date format for your CurrentCulture.

You can use DateTime.TryParseExact with custom format like;

DateTime Test2;
if (DateTime.TryParseExact(textBoxDatumVanStorting.Text, "yyyy/MM/dd", 
                           CultureInfo.InvariantCulture, 
                           DateTimeStyles.None, out Test2))
{
    // Successfull parse
}
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364