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

Asked

Viewed 39 times

1

Hello

I’m having a problem with an MVC project. My View needs to return Data values to some Text Boxes (from the record selection by a Data Table) so that the user can do the record Edit.

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 Data. It is within another JS in the project:

function DatePickerPadrao(control) {
control.datetimepicker(
{
    locale: 'en-US',
    format: 'MM/DD/YYYY'
});
}
  • You can show an example of how the date comes in result.ObsoleteDate?

  • In the Controller Script of this Jsonresult Getdepsecbyid method, the Obsoletedate returns the data {07/11/2018 13:35:26}. However, in the View Textbox where this value is played this string is shown: /Date(1531326926000)/

1 answer

1

Just you take the return and convert to date using parseInt. First remove the bars. See 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());

A suggestion to work with dates is to use moment.js, which has methods to format and convert, simple to use: http://momentjs.com

  • Thanks a lot, it worked! Both your solution and using by Moment.js

Browser other questions tagged

You are not signed in. Login or sign up in order to post.