Validate a date string in C#
This post will discuss how to validate a date string in C#.
The DateTime.TryParseExact() method is the recommended approach to convert the string representation of a date and time to its DateTime
equivalent. It returns a boolean value indicating whether the specified string is converted successfully or not.
The following sample illustrates the simple use of the TryParseExact()
method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
using System; using System.Globalization; public class Example { public static void Main() { string dateString = "06/24/2018 10:00:00 AM -05:00"; CultureInfo enUS = new CultureInfo("en-US"); DateTime dateValue; if (DateTime.TryParseExact(dateString, "MM/dd/yyyy hh:mm:ss tt zzz", enUS, DateTimeStyles.None, out dateValue)) { Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue, dateValue.Kind); } else { Console.WriteLine("'{0}' is not a date or is in invalid format.", dateString); } } } |
Output:
Converted ’06/24/2018 10:00:00 AM -05:00′ to 24-06-2018 08:30:00 PM (Local).
To parse a string representing UTC, you can use the round-trip (O, o) format specifier.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
using System; using System.Globalization; public class Example { public static void Main() { string dateString = "2018-06-24T10:00:00.0805924Z"; DateTime dateValue; if (DateTime.TryParseExact(dateString, "o", CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out dateValue)) { Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue, dateValue.Kind); } else { Console.WriteLine("'{0}' is not in an acceptable format.", dateString); } } } |
Output:
Converted ‘2018-06-24T10:00:00.0805924Z’ to 24-06-2018 10:00:00 AM (Utc).
That’s all about validating a date string in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)