Convert.ToDateTime

时间:2018-05-18 12:47:50

标签: c# asp.net-mvc

我有这段代码:

public JsonResult salvaPaciente(string cns, string sexo, string dataNasc, string nome, string raca,
                                string cep, string ibge, string logradouro, string endereco, string numero,
                                string complemento, string bairro, string telefone, string email)
{
    byte[] bytes = System.Text.Encoding.GetEncoding("iso-8859-8").GetBytes(nome);
    nome = System.Text.Encoding.UTF8.GetString(bytes);

    paciente oPaciente = new paciente()
    {
        bairro = bairro,
        cep = cep,
        cns = cns,
        complemento = complemento,
        dataNasc = Convert.ToDateTime(dataNasc),
        email = email == "" ? " " : email,
        endereco = endereco,
        ibge = ibge,
        logradouro = logradouro,
        nacionalidade = "010",
        nomePaciente = nome,
        numero = numero,
        raca = raca,
        sexo = sexo,
        telefone = telefone
    };
    modelOff.pacientes.Add(oPaciente);
    try
    {
        modelOff.SaveChanges();
        return Json("sim", JsonRequestBehavior.AllowGet);
    }
    catch
    {
        return Json("nao", JsonRequestBehavior.AllowGet);
    }
}

在我确认Visual Studio 2017并生成以下错误后,代码正在运行并崩溃:

  

[FormatException:String未被识别为有效的DateTime。]

字符串dataNasc包含'24 / 06/1979'

2 个答案:

答案 0 :(得分:3)

  

您可以使用DateTime.ParseExact

样品: -

string dataNasc = "24/06/1979";
DateTime time = DateTime.ParseExact(dataNasc, "dd/MM/yyyy", null);

Online Example

答案 1 :(得分:1)

24/06/1979将不会转换,因此您需要先解析它。

DateTime Documentation