I have dates in SQL stored as DateTime,
when showing them in a textbox I do this:
txtDateLogged.Text = v.DateLogged.ToString("dd-MM-yyyy");
But when I the update that textbox to write back to SQL Im getting and invalid DateTime error when using this:
if (DateLogged!= "")
{
uInput.DateLogged = Convert.ToDateTime(DateLogged);
}
Im assuming Im missing something in the formatting – the date value is passed into the public void doing the update as a string, then converted in the line above.
Any suggestions?
thanks
T
You need to convert back in the same format that you converted to text, e.g.
See the docs for
DateTime.ParseExactfor more details.Of course, if you could avoid converting to a string representation – or keep the
DateTimeas well – that would be better.If you’re parsing user input you should use
DateTime.TryParseExactinstead, to account for the possibility of invalid data without using exceptions for flow control.