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

前端 未结 5 1834
小鲜肉
小鲜肉 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:49

    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"});
    
    0 讨论(0)
  • 2020-12-18 04:54
    s.theDate = DateTime.ParseExact("06-13-2012", "MM-dd-yyyy", System.Globalization.CultureInfo.InvariantCulture)
    
    0 讨论(0)
  • 2020-12-18 04:54

    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");
    
    0 讨论(0)
  • 2020-12-18 04:55

    Try this:

    DateTime.ParseExact("06-13-2012", "MM-dd-yyyy", System.Globalization.CultureInfo.InvariantCulture)
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题