Reputation: 65
How can I verify that strings are in the format "dd.MM.yyyy HH:mm:ss.mmm"
?
For example:
12.01.2011 13:26:10.000 13.05.2010 22:30:20.000
should be accepted, others should be rejected. I want to be able to do something like:
string c = "12.01.2011 13:26:10.000";
if (string.CompareFormat(c))
{
// do something
}
else
{
// do something else
}
Upvotes: 0
Views: 174
Reputation: 60246
Use TryParseExact
with your required date format. This will make sure that only this specific format is matched, in contrast to the normal Parse
/TryParse
.
string c = "12.01.2011 13:26:10.000";
DateTime result;
if (DateTime.TryParseExact(c, "dd.MM.yyyy HH:mm:ss.fff", CultureInfo.InvariantCulture, DateTimeStyles.None, out result)) {
// do something
} else {
// do something else
}
Upvotes: 1
Reputation: 26300
You can use TryParseExact
:
string format = "dd.MM.yyyy HH:mm:ss.fff";
string c = "12.01.2011 13:26:10.000";
CultureInfo enUS = new CultureInfo("en-US");
DateTime result;
if (DateTime.TryParseExact(c, format, enUS, DateTimeStyles.None, out result))
{
Console.WriteLine("Right Format");
}
else
{
Console.WriteLine("Wrong Format");
}
Upvotes: 2
Reputation: 4127
try
{
string c = "12.01.2011 13:26:10.000";
DateTime dt = Convert.ToDateTime(c.ToString());
}
catch (Exception ex)
{
//Rejected
}
when it is not in datetime format exception will occur
or can use TryParse
string c = "12.01.2011 13:26:10.000";
DateTime dt;
if(!DateTime.TryParse(c,out dt))
{
//rejected
}
Upvotes: 0