String was not recognized as a valid DateTime?

后端 未结 4 530
青春惊慌失措
青春惊慌失措 2021-01-20 02:31

I try to convert string to datetime but each time I get :

String was not recognized as a valid DateTime.

Code is:

4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-20 02:49

    You are specifying MM when you only have a single digit. Either use just a single M, or pad left with zero using the PadLeft function.

    The following code demonstrates this with both dd and MM padded as desired

    string format = "dd/MM/yyyy";
    string mydate = "12/4/2012";
    DateTime t = DateTime.ParseExact(mydate.Split('/')[0].PadLeft(2,'0') + "/" + 
                                     mydate.Split('/')[1].PadLeft(2,'0') + "/" + 
                                    mydate.Split('/')[2], format, CultureInfo.InvariantCulture);
    

    Output is:

    12/04/2012 00:00:00
    

提交回复
热议问题