Enforcing date pattern with DateTime.TryParseExact method

Hello friends,

Today we will go though a useful method of datetime class called TryParseExact.  You can use this method to specify the pattern in which you want user to enter the dates. There are two overloads as following.

TryParseExact(String, String, IFormatProvider, DateTimeStyles, DateTime)
TryParseExact(String, String[], IFormatProvider, DateTimeStyles, DateTime)

Example: var isValid = DateTime.TryParseExact(Convert.ToString(value), “d MMM yyyy”, CultureInfo.CurrentCulture,
DateTimeStyles.None, out dateTime);

Here if user enter date like 1-Jan-2018, if will be true else false. Please note that 
MMM is case sensitive and mmm will not work.

Hope you found this post useful. Please share your comments.

Leave a comment

Your email address will not be published. Required fields are marked *