String was not recognized as a valid DateTime during insert

后端 未结 3 1564
别那么骄傲
别那么骄傲 2021-01-26 08:21

I get the following error when i try to convert to date time.

String was not recognized as a valid DateTime.

 cost.b_date =          


        
相关标签:
3条回答
  • 2021-01-26 08:55

    Try using DateTime.ParseExact.

    DateTime date = DateTime.ParseExact(c_date.Text, "yyyy/MM/dd", null);
    
    0 讨论(0)
  • 2021-01-26 09:00

    Using string.Format when the input is a string is pointless.

    If you know the format of the string, you should use DateTime.ParseExact or DateTime.TryParseExact. For example, for the string you've got, you could use:

    DateTime date = DateTime.ParseExact(text, "MM/dd/yyyy",
                                        CultureInfo.InvariantCulture);
    

    You should consider:

    • Is this user input? If so, use TryParseExact to detect user error more easily without an exception.
    • Do you definitely know the exact format? If not, using DateTime.TryParse may be more appropriate.
    • Do you definitely know the culture? If it's not the culture of the current thread, you should specify it explicitly.
    • Do you have to get the value as text to start with? If you could use an alternative form of input which gives you the value as a DateTime to start with, that would be preferable.
    0 讨论(0)
  • CultureInfo provider = CultureInfo.InvariantCulture;
    DateTime result = DateTime.ParseExact(c_date.Text, "d", provider);
    
    0 讨论(0)
提交回复
热议问题