Decimal values recognized as DateTime instead of returning false from DateTime.Parse

Check the official documentation on ParseExact

If you know the exact representation you can do something like this:

  format = "ddd dd MMM yyyy h:mm tt zzz";
  try {
     result = DateTime.ParseExact(dateString, format, provider);
     Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
  }
  catch (FormatException) {
     Console.WriteLine("{0} is not in the correct format.", dateString);
  }

If you don't know it, then you are stuck with the cultural convetions

Parse a date and time string by using the conventions of a specific culture. Parse(String, IFormatProvider) overload (see Parsing and Cultural Conventions)


"How to validate string to know its a valid date?"

The issue is that "3.5" is considered a valid date (and also a decimal).

If you want the decimal type to always "win" (i.e. you don't want isDate and isDecimal to both be true), include a decimal check in your validation.

One way to do it is to use the TryParse methods (which return a bool if a string can be parsed to the type, and which sets an out parameter to the converted value) to determine if the string can be converted to a type, for example:

string val = "3.5";

// temp variables to hold parsed values
DateTime tmpDate;
decimal tmpDec;
int tmpInt;

var isDecimal = decimal.TryParse(val, out tmpDec);
var isInteger = int.TryParse(val, out tmpInt);

// When checking if it's a DateTime, make sure it's not also a decimal
var isDate = !isDecimal && DateTime.TryParse(val, out tmpDate);

Tags:

C#

.Net

Datetime