0

I have this array:

["2019-01-01", "2019-01-02", "2019-01-03"]

but I need the dates to be like this:

["01-01-2019", "02-01-2019", "03-01-2019"]

This is how far I got:

var newdate= Date.parse(olddate);
console.log(newdate.toString('dd-MMM-yyyy'));

I get this error:

Uncaught RangeError: toString() radix argument must be between 2 and 36

Thank you

  • 1
    `toString` does not support supplying a format. If you want to specify format like so, you need to use Moment.js or some other implementation, it's simply not possible with vanilla JS. If you simply need to swap the positions in strings and you know the strings represent a valid date, you can use string manipulation. – VLAZ Nov 25 '19 at 09:23
  • `arr=arr.map(d => d.replace(/(\d{4})-(\d{1,2})-(\d{1,2})/,"$3-$2-$1"))` – mplungjan Nov 25 '19 at 09:33

2 Answers2

3

One option would be to map the input array to a new array of date strings with the required format like so:

const input = ["2019-01-01", "2019-01-02", "2019-01-03"];

const output = input.map((str) => {
  
  /* Split date string into sub string parts */
  const [year, month, date] = str.split("-");
  
  /* Compose a new date from sub string parts of desired format */
  return `${date}-${month}-${year}`;      
});

console.log(output);

Here, each date string from input is split by the "-" into year, month and date sub strings. A new date string with the desired format is then composed from the previously extracted sub strings and returned from the map callback.

Dacre Denny
  • 29,664
  • 5
  • 45
  • 65
  • Though this answers question, it has been answered number of times. So the answer is not required and not incorrect. So please choose to close post as duplicate instead of answering – Rajesh Nov 25 '19 at 09:25
0

You could use a library like momentjs https://momentjs.com/guides/ and do it as below.

var dates = ["2019-01-01", "2019-01-02", "2019-01-03"];
var formate = input.map((date) => {
  return moment(moment(date)).format('DD-MM-YYYY');      
});

console.log(formate);
semuzaboi
  • 4,972
  • 5
  • 20
  • 35
luckysoni
  • 59
  • 4