regex
-
Not with regular expressions! :laugh: Use DateTime.TryParseExact[^] to validate the string against your required format. However, there's a small problem. Your "valid" string doesn't actually match the format you're validating against. Your format requires the letter "T" between the date and time, but neither of your strings have that.
string input = "2017-09-19T08:04:31.123";
DateTime parsedDate;
bool isValid = DateTime.TryParseExact(input,
"yyyy-MM-ddThh:mm:ss.fff",
CultureInfo.InvariantCulture,
DateTimeStyles.AssumeUniversal,
out parsedDate);/*
isValid: true
parsedDate: 2017-09-19 09:04:31.123 UTC
*/
"These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer
-
DateTime dt = DateTime.ParseExact(input, "yyyy-MM-dd hh:mm:ss.fff", CultureInfo.InvariantCulture);
-
DateTime dt = DateTime.ParseExact(input, "yyyy-MM-dd hh:mm:ss.fff", CultureInfo.InvariantCulture);
In practice, you would wrap a call to DateTime.ParseExact in a try/catch block ... because it will throw an error if it fails.
«While I complain of being able to see only a shadow of the past, I may be insensitive to reality as it is now, since I'm not at a stage of development where I'm capable of seeing it.» Claude Levi-Strauss (Tristes Tropiques, 1955)
-
In practice, you would wrap a call to DateTime.ParseExact in a try/catch block ... because it will throw an error if it fails.
«While I complain of being able to see only a shadow of the past, I may be insensitive to reality as it is now, since I'm not at a stage of development where I'm capable of seeing it.» Claude Levi-Strauss (Tristes Tropiques, 1955)
Better to use
TryParseExact
, which won't. :-D
"These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer