Date value from Jsonresult function 18/11/2018 00:00:00 javascript gets "/Date(1542506400000)/"

Asked

Viewed 60 times

0

I’m having trouble receiving a function JsonResult that returns me a certain date and this date I am unable to pass to the Date field of my screen for reasons of coming a value other than field formatting.

Function C# JsonResult is replaced by the following: 18/11/2018 00:00:00

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

Like I do for the country

document.getElementById("AnuncioDataFim").value = n.AnuncioDataFim;

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 inside Date is the amount of milliseconds since 01/01/1970 00:00:00 UTC.

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

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));

Browser other questions tagged

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