How to use parse () method in javascript?

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 to Dec , it works perfectly.

I would like to know how to solve, since my webService returns Dez .

    
asked by anonymous 20.12.2016 / 17:25

1 answer

2

Date.parse expects a string representation of dates in the 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 can be a solution is to rename the months before parsing, 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);
    
20.12.2016 / 17:32