Have you ever faced a situation while developing the code where you need to enforce the data format of a certain kind?
If yes, you might want to try a useful method of DateTime class called TryParseExact.
You can use this method to specify the pattern in which you want the user to enter the dates.
There are two overloads as following.
- TryParseExact(String, String, IFormatProvider, DateTimeStyles, DateTime)
- TryParseExact(String, String[], IFormatProvider, DateTimeStyles, DateTime)
How to use it?
Below is an example of how we can use it.
- var isValid = DateTime.TryParseExact(Convert.ToString(value), “d MMM yyyy”, CultureInfo.CurrentCulture, DateTimeStyles.None, out dateTime);
Here, if a user enters a date as 1-Jan-2018, it will either be true or false.
Please note that MMM is case-sensitive and "mmm" will not work.
Hope you found this post useful. Please share your comments.