I am inserting a date into my database, the value which comes from:
s.theDate = Convert.ToDateTime(\"06-13-2012\");
and I get the error, \"
Just use ParseExact
as already suggested or populate Convert.ToDateTime
with the second parameter:
Convert.ToDateTime("06-13-2012", new DateTimeFormatInfo{FullDateTimePattern = "MM-dd-yyyy"});
s.theDate = DateTime.ParseExact("06-13-2012", "MM-dd-yyyy", System.Globalization.CultureInfo.InvariantCulture)
There is a global standard called ISO 8601 that you may (imo should) use. Using this standard, this is what you will end up with.
Convert.ToDateTime("2012-06-03");
Try this:
DateTime.ParseExact("06-13-2012", "MM-dd-yyyy", System.Globalization.CultureInfo.InvariantCulture)
Looking at the behaviour of ToString
on a DateTime
type using an InvariantCulture
, this:
new DateTime(2012, 6, 13).ToString(CultureInfo.InvariantCulture)
results in:
06/13/2012 00:00:00
So, conversely, one can assume that parsing the date with an invariant culture works Ok:
Convert.ToDateTime("06-13-2012", CultureInfo.InvariantCulture)
... and it does.
That being said, assuming date/time formats is a little dangerous. I'd say you want formats to be culture-specific when the UI is considered. Otherwise, you would want formats to be culture-agnostic. Although Microsoft have adopted MM/dd/yyyy as a culture-agnostic format, it's an ambiguous format which isn't something that I would want to build a large system on.