Validating a valid date using the DateTime.TryParse method

I use the Datetime.TryParse method to check the actual time. The input date string will be any string data. but returns false as an invalid date.

 DateTime fromDateValue; if (DateTime.TryParse("15/07/2012", out fromDateValue)) { //do for valid date } else { //do for in-valid date } 

Edit: I missed. I need to check a valid date with a time like "07/15/2012 12:00:00".

Any suggestions are welcome ....

+8
c # datetime tryparse
source share
3 answers

You can use the TryParseExact method, which allows you to pass a collection of possible formats that you want to support. The TryParse method is TryParse dependent, so be very careful if you decide to use it.

So for example:

 DateTime fromDateValue; string s = "15/07/2012"; var formats = new[] { "dd/MM/yyyy", "yyyy-MM-dd" }; if (DateTime.TryParseExact(s, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out fromDateValue)) { // do for valid date } else { // do for invalid date } 
+21
source share

You should use TryParseExact , since you seem to have a fixed format in your case.

Something like may also work for you

 DateTime.ParseExact([yourdatehere], new[] { "dd/MM/yyyy", "dd/M/yyyy" }, CultureInfo.InvariantCulture, DateTimeStyles.None); 
0
source share

As others have said, you can use TryParseExact .

For more information and usage over time, you can check the MSDN Documentation

0
source share

All Articles