DateTime TryParse problem
string date = txtWorkingDate.Text;
DateTime dateTime = DateTime.MinValue;
if (DateTime.TryParse(date, out dateTime))
{
开发者_如何学JAVA args.IsValid = true;
}
else
args.IsValid = false;
txtWorkingDate.Text is like "dd.MM.yyyy" becouse of this validateion is always false if date is not like "dd.MM.yyyy". How c an i check types of date like "dd.MM.yyyy", "MM/dd/yyyy" becouse are all valid.
By using this overload and providing the accepted formats:
string date = txtWorkingDate.Text;
DateTime dateTime;
string[] formats = new[] { "dd.MM.yyyy", "MM/dd/yyyy" };
if (DateTime.TryParseExact(date, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTime))
{
args.IsValid = true;
}
else
{
args.IsValid = false;
}
System.Globalization.CultureInfo cultureinfo =
new System.Globalization.CultureInfo("en-gb");
DateTime dt = DateTime.Parse("13/12/2009", cultureinfo);
You need to specify the culture assuming you know it.
You can use the
DateTime.TryParse(
string s,
IFormatProvider provider,
DateTimeStyles styles,
out DateTime result
)
overload.
Also, you don't need the if, you can simply write
args.IsValid = DateTime.TryParse(...);
As DateTime.TryParse()
already returns a bool.
精彩评论