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
?
https://msdn.microsoft.com/es-es/library/h9b85w22(v=vs.110).aspx
string[] formats= {"M/d/yyyy h:mm:ss tt", "M/d/yyyy h:mm tt",
"MM/dd/yyyy hh:mm:ss", "M/d/yyyy h:mm:ss",
"M/d/yyyy hh:mm tt", "M/d/yyyy hh tt",
"M/d/yyyy h:mm", "M/d/yyyy h:mm",
"MM/dd/yyyy hh:mm", "M/dd/yyyy hh:mm"};
string[] dateStrings = {"5/1/2009 6:32 PM", "05/01/2009 6:32:05 PM",
"5/1/2009 6:32:00", "05/01/2009 06:32",
"05/01/2009 06:32:00 PM", "05/01/2009 06:32:00"};
DateTime dateValue;
foreach (string dateString in dateStrings)
{
if (DateTime.TryParseExact(dateString, formats,
new CultureInfo("en-US"),
DateTimeStyles.None,
out dateValue))
Console.WriteLine("Converted '{0}' to {1}.", dateString, dateValue);
else
Console.WriteLine("Unable to convert '{0}' to a date.", dateString);
}
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.
you could always try:
Regex r = new Regex(@"\d{2}/\d{2}/\d{4}");
r.isMatch(inputString);
this will check that the string is in the format "02/02/2002" you may need a bit more if you want to ensure that it is a valid date like dd/mm/yyyy
Use an array of valid dates format, check docs:
string[] formats = { "d/MM/yyyy", "dd/MM/yyyy" };
DateTime parsedDate;
var isValidFormat= DateTime.TryParseExact(inputString, formats, new CultureInfo("en-US"), DateTimeStyles.None, out parsedDate);
if(isValidFormat)
{
string.Format("{0:d/MM/yyyy}", parsedDate);
}
else
{
// maybe throw an Exception
}
I think one of the solutions is to use DateTime.ParseExact or DateTime.TryParseExact
DateTime.ParseExact(dateString, format, provider);
source: http://msdn.microsoft.com/en-us/library/w2sa9yss.aspx
You can use below IsValidDate():
public static bool IsValidDate(string value, string[] dateFormats)
{
DateTime tempDate;
bool validDate = DateTime.TryParseExact(value, dateFormats, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None, ref tempDate);
if (validDate)
return true;
else
return false;
}
And you can pass in the value and date formats. For example:
var data = "02-08-2019";
var dateFormats = {"dd.MM.yyyy", "dd-MM-yyyy", "dd/MM/yyyy"}
if (IsValidDate(data, dateFormats))
{
//Do something
}
else
{
//Do something else
}
Try this
DateTime dDate;
dDate = DateTime.TryParse(inputString);
String.Format("{0:d/MM/yyyy}", dDate);
see this link for more info. http://msdn.microsoft.com/en-us/library/ch92fbc1.aspx
Source: Stackoverflow.com