I want to check whether a string
contains dates such as 1/01/2000
and 10/01/2000
in dd/MM/yyyy
format.
So far I have tried this.
DateTime dDate = DateTime.Parse(inputString); string.Format("{0:d/MM/yyyy}", dDate);
But how can I check if that format is correct to throw an exception
?
Use the DateTime. TryParseExact method in C# for Date Format validation. They method converts the specified string representation of a date and time to its DateTime equivalent. It checks whether the entered date format is correct or not.
Use DateTime. TryParseExact to try to parse it: string text = "02/25/2008"; DateTime parsed; bool valid = DateTime. TryParseExact(text, "MM/dd/yyyy", CultureInfo.
One way to check if a string is date string with JavaScript is to use the Date. parse method. Date. parse returns a timestamp in milliseconds if the string is a valid date.
string inputString = "2000-02-02"; DateTime dDate; if (DateTime.TryParse(inputString, out dDate)) { String.Format("{0:d/MM/yyyy}", dDate); } else { Console.WriteLine("Invalid"); // <-- Control flow goes here }
you can use DateTime.ParseExact
with the format string
DateTime dt = DateTime.ParseExact(inputString, formatString, System.Globalization.CultureInfo.InvariantCulture);
Above will throw an exception if the given string not in given format.
use DateTime.TryParseExact
if you don't need exception in case of format incorrect but you can check the return value of that method to identify whether parsing value success or not.
check Custom Date and Time Format Strings
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With