I get the following error when i try to convert to date time.
String was not recognized as a valid DateTime.
cost.b_date = DateTime.Parse(c_date.Text) ;//c_date.Text = 12/28/2012
Then i try
string date = string.Format("{0:yyyy-MM-dd}",c_date.Text);
cost.b_date = DateTime.Parse(date) ;
but i get the same exception how to fix this problem.
Using string.Format
when the input is a string is pointless.
If you know the format of the string, you should use DateTime.ParseExact
or DateTime.TryParseExact
. For example, for the string you've got, you could use:
DateTime date = DateTime.ParseExact(text, "MM/dd/yyyy",
CultureInfo.InvariantCulture);
You should consider:
- Is this user input? If so, use
TryParseExact
to detect user error more easily without an exception. - Do you definitely know the exact format? If not, using
DateTime.TryParse
may be more appropriate. - Do you definitely know the culture? If it's not the culture of the current thread, you should specify it explicitly.
- Do you have to get the value as text to start with? If you could use an alternative form of input which gives you the value as a
DateTime
to start with, that would be preferable.
CultureInfo provider = CultureInfo.InvariantCulture;
DateTime result = DateTime.ParseExact(c_date.Text, "d", provider);
Try using DateTime.ParseExact.
DateTime date = DateTime.ParseExact(c_date.Text, "yyyy/MM/dd", null);
来源:https://stackoverflow.com/questions/14089917/string-was-not-recognized-as-a-valid-datetime-during-insert