【问题标题】:Convert String to DateTime C# ASP.NET将字符串转换为日期时间 C# ASP.NET
【发布时间】:2017-09-13 03:11:36
【问题描述】:

我在尝试将字符串转换为 DateTime 时遇到问题。我尝试了一些方法,但在尝试更新记录时不断出现错误。

string consentGiven = ConsentGivenDate.Text;
DateTime date1 = Convert.ToDateTime(consentGiven);
cmd.Parameters.Add(new SqlParameter("@ConsentGivenDate", date1));

if ((ConsentGivenDate.Text == "dd/mm/yyyy"))
    cmd.Parameters.Add("@ConsentGivenDate", SqlDbType.DateTime).Value = DBNull.Value;
else
    cmd.Parameters.Add("@ConsentGivenDate", SqlDbType.DateTime).Value = ConsentGivenDate.Text;

我尝试添加一些格式,使日期为英国格式“dd/mm/yyyy”,但仍无法转换。

我做错了什么?

我是一个真正的编码新手,所以如果它是愚蠢的东西道歉......

【问题讨论】:

  • 如果数据库中的列是DateTime,为什么要插入字符串?只需cmd.Parameters.Add("@ConsentGivenDate", SqlDbType.DateTime).Value = date1

标签: c# asp.net string datetime


【解决方案1】:

始终在 Sql 参数中使用正确类型的实例。当参数与数据库架构中的DateDateTime 对应时,对应的.net 类型应为DateTime 而不是string

object sqlValue = DBNull.Value;
DateTime dateConsentGiven;

if(DateTime.TryParseExact(ConsentGivenDate.Text, "dd/mm/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out dateConsentGiven))
    sqlValue = dateConsentGiven;
cmd.Parameters.Add("@ConsentGivenDate", SqlDbType.DateTime).Value = sqlValue;

另请注意,您在问题的原始代码中多次添加相同的参数,Sql Server 使用命名参数,这意味着参数名称是唯一的。

【讨论】:

    【解决方案2】:
    DateTime dt = DateTime dt=DateTime.ParseExact("ConsentGivenDate.Text", "dd/MM/yyyy", CultureInfo.InvariantCulture);
    cmd.Parameters.Add(new SqlParameter("@ConsentGivenDate", dt));
    cmd.Parameters.Add("@ConsentGivenDate", SqlDbType.DateTime).Value = DBNull.Value;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多