Sreedhar
Sreedhar

Reputation: 30045

Validate Input DateTime C#

How can I validate the DateTime (input) to be in format of DD/MM/YYYY HH:MM in C#

I need to throw an error if the specified format doesn't match the above one.

Upvotes: 0

Views: 2266

Answers (2)

Denis Ivin
Denis Ivin

Reputation: 5644

You could also try DateTime.ParseExact - this automatically throws FormatException if the input is not in specified format:

var dt = DateTime.ParseExact(dtString, "dd/MM/yyyy hh:mm", new CultureInfo("en-US"));

Upvotes: 0

Adriaan Stander
Adriaan Stander

Reputation: 166606

Have a look at using DateTime.TryParseExact Method

Converts the specified string representation of a date and time to its DateTime equivalent using the specified format, culture-specific format information, and style. The format of the string representation must match the specified format exactly. The method returns a value that indicates whether the conversion succeeded.

Upvotes: 1

Related Questions