Convert text to datetime?
I want to c开发者_StackOverflow中文版onvert text to datetime but having error.My text box value is in format dd/MM/yyyy String was not recognized as a valid DateTime.
myFtMaster.GENTRTYDATEFROM =Convert.ToDateTime(txtTreatyPeriodfrom.Text.ToString());
My business object 'gentrtydatefrom' datatype is DateTime. Also what is the best way to avoid these type of errors without using a Try catch block.
You either specify a culture that uses that specific format:
myFtMaster.GENTRTYDATEFROM = Convert.ToDateTime(
txtTreatyPeriodfrom.Text, CultureInfo.GetCulture("en-GB")
);
or use the ParseExact
method:
myFtMaster.GENTRTYDATEFROM = DateTime.ParseExact(
txtTreatyPeriodfrom.Text, "dd/MM/yyyy", CultureInfo.Invariant
);
The ParseExact
method only accepts that specific format, while the Convert.ToDateTime
method still allows some variations on the format, and also accepts some other date formats.
To catch illegal input, you can use the TryParseExact
method:
DateTime d;
if (DateTime.TryParseExact(txtTreatyPeriodfrom.Text, "dd/MM/yyyy", CultureInfo.Invariant, DateTimeStyles.None, out d)) {
myFtMaster.GENTRTYDATEFROM = d;
} else {
// communcate the failure to the user
}
Use something like the following instead:
DateTime date = DateTime.MinValue;
DateTime.TryParse(txtTreatyPeriodfrom.Text, out date);
TryParse is similar to DateTime.Parse()
but it does not throw an exception if the conversion fails.
If you want to use the en-CA specific culture use the following:
DateTime.TryParse(txtTreatyPeriodfrom.Text, new CultureInfo("en-CA"),
DateTimeStyles.AllowWhiteSpaces, out date);
Then obviously deal with those dates that fail to parse.
Ensuring the user is prompted on the format will obviously reduce mistakes.
Have a look at
DateTime.TryParse(String value, out DateTime, [culture settings])
精彩评论