Date value coming from JsonResult function 18/11/2018 00:00:00 javascript receives "/ Date (1542506400000) /" [duplicate]

0

I'm having trouble receiving a JsonResult function that returns me a certain date and this date I'm not able to move to the Date field of my screen for reasons other than the formatting of the field.

The function C # JsonResult passes the following value: 18/11/2018 00:00:00

  

My Javascript function receives "/ Date (1542506400000) /"

How do I make the field

document.getElementById("AnuncioDataFim").value = n.AnuncioDataFim;
    
asked by anonymous 30.10.2018 / 03:44

1 answer

2

You would have to see if you can configure how dates are serialized in C #, but you can convert the received value into JS because the integer that is within Date is the amount of milliseconds from 01/01/1970 00:00:00 UTC .

Using a regex you could take this number and use it in the Date and then format the date as you see fit.

Example:

function parseDate(dateString) {
  let result = /Date\((\d+)\)/.exec(dateString)
  
  // Se não seguir o padrão da Regex retorna null
  if (!result) {
    return null;
  }
  
  let miliseconds = parseInt(result[1], 10);
  let date = new Date(miliseconds);
  
  return '${date.getDate()}/${date.getMonth() + 1}/${date.getFullYear()}';
}

// 18/11/2018
let date_1 = "/Date(1542506400000)/";  // 
console.log(date_1 + " == " + parseDate(date_1));

// 30/10/2018
let date_2 = "/Date(1540899418346)/"
console.log(date_2 + " == " + parseDate(date_2));
    
30.10.2018 / 12:41