Parse Simple DateTime

后端 未结 3 911
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-17 19:40
DateTime dt = DateTime.ParseExact(\"1122010\", \"Mddyyyy\", System.Globalization.CultureInfo.CurrentCulture);

Throwing this exception: String was

相关标签:
3条回答
  • 2021-01-17 19:42

    The problem is that you are not giving ParseExact enough information to work with.

    "M" means a 1 or 2 digit month. But your string starts with "1122". Is that January 12th or November 22nd?

    The only solution, as Anthony shows, is to pad with a 0 when needed.

    0 讨论(0)
  • 2021-01-17 20:00

    I suggest using the format "MMddyyyy" and ensuring your input parameter has at least 8 characters. Example:

    DateTime dt = DateTime.ParseExact("1122010".PadLeft(8, '0'), "MMddyyyy", System.Globalization.CultureInfo.CurrentCulture);
    

    If you are using a data source with the leading 0 missing for the month, this will add it where required.

    0 讨论(0)
  • 2021-01-17 20:01

    The single "M" format string is unacceptable because not all months can be uniquely represented with a single digit or character. As previously suggested, you will have to use "MMddyyyy" and pad the left string when necessary.

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