0

I have a datetimepicker and i save the date selected with a Save Button in my SQLServer with this code. For some reason i need to have a nullable DateTime:

clienteAdd.DataLead = string.IsNullOrEmpty(form["dataLead"]) ? (DateTime?)null : DateTime.Parse(form["dataLead"]);

The save function works fine, the problem is when i set the datetimepicker loaded. I recover the data from SQLServer with this code:

var elemento = new{ dataLead = clienteLead.DataLead }

I sent 'elemento' to the view from JQuery and i set the datetimepicker:

$('#dataLead').datepicker('setDate', (new Date(result.dataLead)));

When i set 'dataLead' i have NaN as date. I know the problem is the conversion of datetime but i don't know how to save and after load this data.

Thanks to all

1 Answers1

0

From the docs here, Javascript's Date object can recive either milliseconds which is a number or a dateString. My guess is that result.dataLead is an object since you DataLead is an object (a c# DateTime). That's why you can't do the assignment you want.

The answer here explains how to get the millis from a DateTime.

Try the following code (untested):

var elemento = new{ dataLead = (long)clienteLead.DataLead.TotalMilliseconds }

and then do the regular assignment:

$('#dataLead').datepicker('setDate', (new Date(result.dataLead)));

Update:

Since clientLead.DataLead can be null you have to make sure you won't get a NullPointerException when doing (long)clienteLead.DataLead.TotalMilliseconds and maybe consider checking that typeof result.dataLead != "undefined" in the javascript

Community
  • 1
  • 1
Guy Grin
  • 1,968
  • 2
  • 17
  • 38