系统.FormatException:字符串没有被识别为有效的日期时间.在System.DateTimeParse.Pa

本文关键字:时间 日期 System Pa DateTimeParse 有效 字符串 FormatException 识别 系统 | 更新日期: 2023-09-27 18:02:17

sqlparameters for date for birth

 SqlParameter dayParameter = new SqlParameter("@day", SqlDbType.Int);
            SqlParameter monthParameter = new SqlParameter("@month", SqlDbType.Int);
            SqlParameter yearParameter = new SqlParameter("@year", SqlDbType.Int);

日、月、年转换

 dayParameter.Value = Convert.ToString(Convert.ToDateTime(Jfunctionparents.GetSystemDate().Substring(0, 2)));
        monthParameter.Value = Convert.ToString(Convert.ToDateTime(Jfunctionparents.GetSystemDate().Substring(3,2)));
        yearParameter.Value = Convert.ToString(Convert.ToDateTime(Jfunctionparents.GetSystemDate().Substring(6,4)));
类jfunction

 public class Jfunctionparents
{
    public static string GetSystemDate()
    {
        return Convert.ToString(System.DateTime.Today.ToString("d"));
    }
    public static string GetSystemTime()
    {
        return Convert.ToString(System.DateTime.Today.ToString("t"));
    }

在提交

时显示此错误
System.FormatException: String was not recognized as a valid DateTime. at System.DateTimeParse.Parse(String s, DateTimeFormatInfo dtfi, DateTimeStyles styles) at System.Convert.ToDateTime(String value) 

系统.FormatException:字符串没有被识别为有效的日期时间.在System.DateTimeParse.Pa

语句
dayParameter.Value = Convert.ToString(Convert.ToDateTime(Jfunctionparents.GetSystemDate().Substring(0, 2)));

看起来逻辑错误,系统无法将Jfunctionparents.GetSystemDate().Substring(0, 2)的输出转换为DateTime,因为它是长度为2的字符串。

我想你这里想要的只是一天,所以没有必要将Jfunctionparents.GetSystemDate().Substring(0, 2)转换为DateTime

语句应该看起来像:

dayParameter.Value = Int32.Parse(Jfunctionparents.GetSystemDate().Substring(0, 2));
monthParameter.Value = Int32.Parse(Jfunctionparents.GetSystemDate().Substring(3,2));
yearParameter.Value = Int32.Parse(Jfunctionparents.GetSystemDate().Substring(6,4));