Currently I'm having hard time finding how to resolve my problem related to the DateTime.TryPase function
String formattedDateString = String.Empty;
// German date dd.mm.yyyy
string dateString = "14.03.2016";
DateTimeFormatInfo dateTimeFormat = null;
//automatically throws and exception if the locale is not in the correct format
CultureInfo fromCulture = new CultureInfo("en-US");
DateTime tryParseDateTime;
//automatically throws and exception if the locale is not in the correct format
CultureInfo toCulture = new CultureInfo("de-de");
dateTimeFormat = toCulture.DateTimeFormat;
// expecting result to fail
if (DateTime.TryParse(dateString, fromCulture, DateTimeStyles.None, out tryParseDateTime))
{
formattedDateString = tryParseDateTime.ToString("d", dateTimeFormat);
Console.WriteLine("success");
}
else
{
Console.WriteLine("Failed");
}
So here in my Code, I'm sending German format date ie dd.mm.yyyy and expecting the DateTime.TryParse to fail but since the day is below 12, it assumes that has month and returns the success statement.
If I pass the German date "15.03.2016" this works fine.
How can I resolve my problem here.
Here the requested locale is German
Thanks
Note: The questioner expects the conversion to fail with the given German format input string. He only wants the conversion to succeed when the input string is NOT in the German format but in the US format.
Use DateTime.TryParseExact
and pass in the expected format from your source culture.
// German date dd.mm.yyyy
string dateString = "01.03.2016";
CultureInfo fromCulture = new CultureInfo("en-US");
DateTime tryParseDateTime;
// expecting result to fail
if (DateTime.TryParseExact(dateString, fromCulture.DateTimeFormat.ShortDatePattern, fromCulture, DateTimeStyles.None, out tryParseDateTime))
{
MessageBox.Show("Success");
}
else
{
MessageBox.Show("Failed");
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.