为什么我无法将字符串转换为DateTime?
我不能转换这个字符串,任何人都可以帮助我吗?为什么我无法将字符串转换为DateTime?
[WebMethod]
public void InsertUsuario(string usuario, string senha, string nome, string dtnasc, string fone, string email, int oab, string endereco, string bairro, string cep, int codcidade, string cpf, string cnpj)
{
using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
{
string chav = "asfasdf";
DateTime d = DateTime.ParseExact(dtnasc, "yyyy'-'MM'-'dd'T'HH':'mm", CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal);
SqlCommand command = new SqlCommand("INSERT Into Usuarios (IdUsuario, Usuario, Senha, Nome, Chave, DtNasc, Fone, Email, OAB, Endereco, Bairro, CEP, CodCidade, CPF, CNPJ) VALUES ((Select MAX(idusuario)+1 from Usuarios), '" + usuario + "', '" + senha + "', '" + nome + "', '" + chav + "', '"+d+ "', '" + fone + "', '" + email + "', " + oab + ", '" + endereco + "', '" + bairro + "', '" + cep + "', " + codcidade + ", '" + cpf + "','"+cnpj+"')");
//command.Parameters.Add("@dtnasc", SqlDbType.DateTime).Value = DateTime.Now;
command.Connection.Open();
command.ExecuteNonQuery();
}
}
这是出现错误:
System.FormatException:Cadeia德CARACTERESÑãöFOI reconhecida como的日期时间v á利多。
em System.DateTimeParse.ParseExact(String s,String format,DateTimeFormatInfo dtfi,DateTimeStyles style)
em OniPresenteAPI.oni.InsertUsuario(String usuario,String senha,String nome,String dtnasc,String fone,String email,Int32 oab ,字符串endereco,字符串的Bairro,字符串CEP,的Int32 codcidade,CPF的字符串,字符串CNPJ)
基于要传递的的日期字符串注释的问题 “1991年12月21日00:00”分成DateTime.ParseExact()
。异常中的线索正在爆炸,因为第二个参数format
参数不正确。您的参数是"yyyy'-'MM'-'dd'T'HH':'mm"
。正确的格式应该是"yyyy-M-dd hh:mm"
。有文档here的读操作,具体地,本领域:
的 DateTime.ParseExact(字符串,字符串,的IFormatProvider,DateTimeStyles) 方法解析日期的字符串表示,它必须是在所定义的格式 由格式参数。它还要求日期 和s中的时间元素按格式指定的顺序出现。如果s 与format参数的模式不匹配,并且style参数定义了任何 变体,则该方法抛出FormatException。
这是我的工作例如:
using System;
using System.Globalization;
public class Program
{
public static void Main()
{
string dateAsAString = "1991-12-21 00:00";
try
{
DateTime d = DateTime.ParseExact(dateAsAString, "yyyy-M-dd hh:mm", CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal);
Console.WriteLine("The correct Date is " + d.ToString());
}
catch (FormatException)
{
Console.WriteLine("{0} is not in the correct format.", dateAsAString);
}
}
}
的工作dotnetfiddle,以及你与format
字符串玩耍。
*请*使用参数化的SQL。对于SQL注入攻击,您是**开放**。不仅如此,如果你使用参数化SQL,它甚至可以解决这个问题,因为将字符串连接在一起形成一个SQL脚本非常容易打破错误,就像你得到的错误一样。 – Siyual
除了sql注入问题,什么字符串不能被解析?你甚至没有示例。 –
dtnasc的确切值是什么? – dazedandconfused