Convert.DateTime throws error: String was not recognized as a valid DateTime for “06-13-2012”

前端 未结 5 1833
小鲜肉
小鲜肉 2020-12-18 04:21

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, \"

5条回答
  •  时光说笑
    2020-12-18 04:58

    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.

提交回复
热议问题