String was not recognized as a valid DateTime?

后端 未结 4 531
青春惊慌失措
青春惊慌失措 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 03:00

    The desired format is

    string format = "dd/M/yyyy";
    

    I don't understand a thing though, why split an concatenate the string, since you would obtain the same thing?

    If the input is 12/4/2012, after the split by '/', you'll get 12, 4, 2012 and then concatenate them back to obtain "12/4/2012". Why this?

    Also, if you really need that split, you can store in into an array so you don't need to split it 3 times:

    var splits = lbl_TransDate.Text.Split('/');
    DateTime.ParseExact(splits[0] + "/" + splits[1] + "/" + splits[2], ...);
    

    If you don't trust the input, the splits array might not be of Length = 3, and more of it, you can use DateTime.TryParseExact

    EDIT You can use the overload with multiple formats So if the input might be 12/4/2012 or 12/04/2012, you can give both formats

    var formats = new[] {"dd/M/yyyy","dd/MM/yyyy"};
    var date = DateTime.ParseExact("12/4/2012", formats, 
                                            System.Globalization.CultureInfo.InvariantCulture,
                                            System.Globalization.DateTimeStyles.AssumeLocal);
    

提交回复
热议问题