Convert a date from C# (Datetime), which has been transformed JSON, to Javascript Date

Asked

Viewed 59 times

-2

When I perform a data search in C#, it returns the DateTime in format "/Date(123456789)/", but I can’t convert to a valid Javascript date. As a:

var data = new Date("/Date(123456789)/");

Or:

var data = new "/Date(123456789)/".replace("/", "");
  • If you want to handle this in Javascript, it might help: https://answall.com/a/398489/112052

2 answers

0


I recommend using a librarian called Moment, she already takes care of making this conversion for you without needing much effort.

var data = moment(dataDoResponse);
  • Thanks man, in fact it worked perfectly.

0

To solve the problem, we will need to use a regex.

The return of $.Ajax() or $.Post() will be in a variable as below.

$.post("/Area/Controler/Ação", {parametros}, function (retorno) {
console.log(retorno) // "/Date(123456789)/"
        }, "Json");

Then we can take the return variable and convert to date as below

$.post("/Area/Controler/Ação", {parametros}, function (retorno) {
 console.log(new Date(parseInt(retorno.replace(/[a-z A-z () /]/g, ""))));
  //Fri Jan 02 1970 07:17:36 GMT-0300 (Horário Padrão de Brasília)
 console.log(new Date(parseInt(retorno.replace(/[a-z A-z () /]/g, ""))).toLocaleString());
 //"02/01/1970 07:17:36"
                        }, "Json");
  • A-z ("A" uppercase and "z" lowercase) is a range that also considers characters ^, _, [] and others, and the spaces inside the brackets are unnecessary, since the value has no spaces - see. Then it could just be [a-zA-Z()/], see. But if you want to remove everything that is not number, you could use \D, see. But if you want to validate the format (you only take the number if it is in the "/Date(...)/" format), then you can use what I suggested in https://answall.com/a/398489/112052

  • Another detail is to check if C# is generating the value in seconds or milliseconds. O Date Javascript receives the value in milliseconds, but what you used in the tests seems to be in seconds (since the dates generated are in the year 1970)

  • C# sends the values as milliseconds, what I did was just pass some example value. I don’t care about the end of the date, I care about the conversion. .

Browser other questions tagged

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