Convert 20121004 (yyyyMMdd) to a valid date time?

前端 未结 4 1269
被撕碎了的回忆
被撕碎了的回忆 2020-12-25 09:32

I have a string in the following format yyyyMMdd and I am trying to get it to look like this:

yyyy-MM-dd

When I try:



        
4条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-25 10:07

    I get the error:

    FormatException: String was not recognized as a valid DateTime.

    You are getting this error because you are not telling the ToDateTime() method how to figure out to parse your string.

    If you use the following method:

    public static DateTime ParseExact(
        string s,
        string format,
        IFormatProvider provider,
        DateTimeStyles style
    )
    

    You won't get this error. After you generate a DateTime variable just display it in the format yyyy-dd-mm using the ToString() method.

    public string ToString(
        string format,
        IFormatProvider provider
    )
    

    http://msdn.microsoft.com/en-us/library/8tfzyc64
    http://msdn.microsoft.com/en-us/library/9h21f14e

    I know this basically repeats the same information as everyone else but it also provides him the ability to understand what the two methods he needs to use actually does.

提交回复
热议问题