My JavaScript / AJAX function is not converting Date to the correct format

1

Hello

I have a problem with an MVC project. My View needs to return values in Date for some Text Boxes (from the selection of the record by a Data Table) so that the user can edit the record.

The problem is that the data is not being shown in the correct format. TextBoxes show Strange Strings like this in place:

  

/ Date (1515290400000) /

My JavaScript function looks like this:

function GetDepSecById(DepartmentSectionId) {
$.ajax({
    url: urlGetDepSecById,
    data: { DepartmentSectionId: DepartmentSectionId },
    type: 'POST',
    success: function (result) {

        $('#DepartmentSectionId').val(result.DepartmentSectionId);
        $('#ObsoleteDate').val(result.ObsoleteDate);
        $('#StartPeriodDate').val(result.StartPeriodDate);
        $('#EndPeriodDate').val(result.EndPeriodDate);

        DatePickerPadrao($('#ObsoleteDate'));
        DatePickerPadrao($('#StartPeriodDate'));
        DatePickerPadrao($('#EndPeriodDate'));
    }
  });
}

The DataPickerPadrao method is what should be responsible for converting the Data. It is within another JS in the project:

function DatePickerPadrao(control) {
control.datetimepicker(
{
    locale: 'en-US',
    format: 'MM/DD/YYYY'
});
}
    
asked by anonymous 12.07.2018 / 14:57

1 answer

1

Just get the return and convert to date using parseInt . Before you remove the bars. Here's an example:

var retorno = "/Date(1531326926000)/";
// remove as barras com o Regex, ou pode ser um replace também
retorno = retorno.replace(/[^0-9 +]/g, ''); 
// converte o formato numérico para data
var data = new Date(parseInt(retorno));
console.log(data);

//se quiser no formato texto:
console.log(data.getDate() + "/" + (data.getMonth() + 1) + "/" + data.getFullYear());

One suggestion for working with dates is to use moment.js , which has both simple to use methods for formatting and converting: link

    
12.07.2018 / 15:34