How do I use parse() in javascript?

Asked

Viewed 49 times

4

I have the following implementation:

minhaDataRetornada = "Dez 20, 2016";
minhaDataTratada = Date.parse(minhaDataRetornada);
console.log(minhaDataTratada);

Running the above code, my return is :Nan.

If I change the word Dez for Dec, works perfectly.

I’d like to know how to fix it, man webService returns Dez.

1 answer

2


Date.parse expects a date representation string in format RFC2822 or ISO 8601 (other formats may be used, but the results may not be as expected).

In the case of month names, the expected is in English:

Month-name = "Jan" / "Feb" / "Mar" / "Apr" / "May" / "Jun" / "Jul" / "Aug" "Sep" / "Oct" / "Nov" / "Dec"

What might be a solution is to rename the months before parse, something like:

var mesesEn = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug", "Sep","Oct","Nov","Dec"],
    mesesPt = ["Jan","Fev","Mar","Abr","Mai","Jun","Jul","Ago", "Set","Out","Nov","Dez"];

minhaDataRetornada = "Dez 20, 2016";

// verifica se o mês para renomeá-lo
if (mesesPt.indexOf(minhaDataRetornada.split(" ")[0]) !== -1)
  var idx = mesesPt.indexOf(minhaDataRetornada.split(" ")[0]);
  minhaDataRetornada = minhaDataRetornada.replace(mesesPt[idx], mesesEn[idx]);

minhaDataTratada = Date.parse(minhaDataRetornada);
console.log(minhaDataTratada);

Browser other questions tagged

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