无法将字符串识别为有效的日期时间异常

时间:2018-08-16 06:29:43

标签: c# datetime

将datetime转换为varchar时出现上述异常

if (columnDefs[i].IndexOf("Date") > -1)
{
    // Date search
    subQuery += columnDefs[i] + 
                " = '%" + 
                DateTime.Parse(searchValues[i]).ToString("dd/MM/yyyy") + 
                "'" + " and ";
}

1 个答案:

答案 0 :(得分:0)

使用SQL时,不要 hardcode 而是 paramterize 查询;假设您使用的MS SQL具有@parameter_name语法:

if (columnDefs[i].IndexOf("Date") >= 0)
{
    // Date search: we a parameter, not its value into the query
    subQuery += $" ({columnDefs[i]} = @prm_{columnDefs[i]}) and ";
}

...

// when executing the query
using (var myQuery = new SqlQuery(subQuery, myConnection)) {
  // we set parameters' values
  for (int i = 0; i < columnDefs.Count(); ++i) {
    if (columnDefs[i].IndexOf("Date") >= 0) {
      //TODO: check the actual parameter value type (SqlDbType.DateTime?) 
      var prm = new SqlParameter($"@prm_{columnDefs[i]}", SqlDbType.DateTime);
      //TODO: check actual string format (d/M/yyyy?)
      prm.Value = DateTime.ParseExact(
         searchValues[i], 
        "d/M/yyyy", 
         CutureInfo.InvariantCulture);

      myQuery.Parameters.Add(prm);
    }
  }

  ...
}