我无法转换此字符串,有人可以帮我吗?
[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 de caracteres não foi reconhecida como DateTime válido.
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, String endereco, String bairro, String cep, Int32 codcidade, String cpf, String cnpj(
该问题基于您正在将日期字符串"1991-12-21 00:00">传递到DateTime.ParseExact()
的注释。线索在异常中,因为参数format
参数的第二个参数不正确,因此正在爆炸。
您的参数"yyyy'-'MM'-'dd'T'HH':'mm"
。应"yyyy-M-dd hh:mm"
正确的格式。阅读此处的文档,特别是此区域:
这 DateTime.ParseExact(String, String, IFormatProvider, DateTimeStyles( 方法分析日期的字符串表示形式,该表示形式必须位于 格式参数定义的格式。它还要求日期 s 中的时间元素按格式指定的顺序显示。如果 s 与格式参数的模式不匹配,具有任何 由 style 参数定义的变体,该方法将引发 格式异常。
这是我的工作示例:
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);
}
}
}
一个工作的dotnetfidd以及你玩format
弦。