Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking Date format from a string in C#

Tags:

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?

like image 884
User1204501 Avatar asked Sep 26 '13 04:09

User1204501


People also ask

How do you check if a string is a valid date in C#?

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.

How do you check if the date is in dd mm yyyy format in C #?

Use DateTime. TryParseExact to try to parse it: string text = "02/25/2008"; DateTime parsed; bool valid = DateTime. TryParseExact(text, "MM/dd/yyyy", CultureInfo.

How do I check if a string is valid?

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.


2 Answers

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 } 
like image 143
Nadeem_MK Avatar answered Sep 23 '22 12:09

Nadeem_MK


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

like image 21
Damith Avatar answered Sep 23 '22 12:09

Damith