hidden
hidden

Reputation: 3236

c# datetime hour minute validation

11/11/2011 15:04  VALID ANYTHING OUTSIDE OF THIS IS FORMAT INVALID
11/11/11 12:04    INVALID
11/11/2011 15:0   INVALID

I am thinking on min characters to be 16 what else can I do. Other solutions out there?

Upvotes: 2

Views: 1716

Answers (2)

JonVD
JonVD

Reputation: 4268

You should look at TryParseExact and see if the date can be parsed, this is adapted from here.

string dateString = "11/11/2011 15:04"; // <-- Valid
string format = "dd/MM/yyyy HH:mm";
DateTime dateTime;
if (DateTime.TryParseExact(dateString, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTime))
{
  Console.WriteLine(dateTime);
}

The above uses dd and MM which means that it expects a two digit day and month. If you just want one digit just use the singular d / M.

Upvotes: 4

Erik Philips
Erik Philips

Reputation: 54618

I would use:

DateTime parsedValue = DateTime.ParseExact(stringOfDateTime, "MM/dd/yyyy HH:mm")

(although I don't know if your month or days come first since you chose 11 for both)

Upvotes: 3

Related Questions