Method that receives datetime nulleable, change format to MM / dd / yyyy

0

I have a question .. I have a method that receives several dates in datetime format (dd / mm / yyyy)

Something like that

public ActionResult Reports(DateTime? FechaInicio, DateTime? FechaFin, DateTime? IptSemana, DateTime? IptDia)

At the moment of executing the SP, I send the parameters in the following way:

cmd.Parameters.Add("@FechaInicio", SqlDbType.DateTime).Value = FechaInicio;  //? (object)DBNull.Value : FechaFin);
                cmd.Parameters.Add("@FechaFin", SqlDbType.DateTime).Value = FechaFin;  //? (object)DBNull.Value : FechaFin);
                cmd.Parameters.Add("@FechaSemana", SqlDbType.DateTime).Value = IptSemana;//  ? (object)DBNull.Value : IptSemana);
                cmd.Parameters.Add("@FechaDia", SqlDbType.DateTime).Value = IptDia;//  ? (object)DBNull.Value : IptDia);

How can I change the date format to MM / dd / yyyy if I get an error that the datetime is nulleable

    
asked by Richard 10.08.2018 в 00:10
source

2 answers

1

For objects that accept null values, you can access their value from the property "value"

cmd.Parameters.Add("@FechaInicio", SqlDbType.DateTime).Value = FechaInicio.value;

But the best thing here is to make a condition and assign them a value if they are null, for example

if (FechaInicio == null) { FechaInicio = DateTime.Now; }
    
answered by 10.08.2018 / 00:35
source
1

Questions with .HasValue if it has value, then on the value you return the format

  dt.HasValue ? (object)DBNull.Value : dt.Value.ToString("MM/dd/yyyy");

EDITED, full use.

cmd.Parameters.Add("FechaInicio", FechaInicio.HasValue ? (object)DBNull.Value : FechaInicio.Value.ToString("MM/dd/yyyy"));
    
answered by 10.08.2018 в 00:40