3

I'm trying to insert events into a calendar. the problem is my events are structured like this: xx/xx/xxxx and the calendar uses another format xx-xx-xxxx. How do I make this transformation ?

I have transformed the dates from JSON format to a string but I can't change the / into -.

data.forEach(function (element) {

    let date = new Date(element.sessionDate)
    datesArr.push(date.toLocaleDateString())
})

console.log(datesArr)

And now my array looks like this:

0: "12/24/2018"

1: "12/27/2018"

2: "1/3/2019"

3: "1/3/2019"

4: "1/7/2019"

My expected result for the calendar to receive the events should be: ['2019-03-04', '2019-03-08', '2019-03-12', '2019-03-15'].

FranzHuber23
  • 3,311
  • 5
  • 24
  • 63
Raz
  • 189
  • 1
  • 12
  • you can change the date format with datePipe https://angular.io/api/common/DatePipe – Jon Fernandez Apr 08 '19 at 14:33
  • the fastest way would be to use moment.js. I know it's another dependency, but it saves you a lot of headache with string manipulation: https://momentjs.com/ – rufus1530 Apr 08 '19 at 14:38
  • What is "JSON format" for a date, there's nothing in the spec for dates! – phuzi Apr 08 '19 at 14:39
  • Possible duplicate of [Where can I find documentation on formatting a date in JavaScript?](https://stackoverflow.com/questions/1056728/where-can-i-find-documentation-on-formatting-a-date-in-javascript) – Heretic Monkey Apr 08 '19 at 14:51

2 Answers2

2

There are a couple of ways to do this:

The array version

You could replace them using a regex and then glue matched values back together.

const input = '12/24/2018';
const parts = input.split('/');
const output = `${parts[2]}-${parts[0]}-${parts[1]}`;

console.log(new Date(output));

The regex version

You could replace them using a regex and then glue matched values back together.

const input = '12/24/2018';
const output = input.replace(/(\d{1,2})\/(\d{1,2})\/(\d{4})/, '$3-$1-$2');

console.log(new Date(output));

Or using a library like moment.js

lumio
  • 7,428
  • 4
  • 40
  • 56
1

Split the string value by "/" separation gives an array of results. Then join the array with "-" to get the string result back. Use Array.map() to transform into a new array.

const dates = ['2019/03/04', '2019/03/08', '2019/03/12', '2019/03/15'];

const formattedDates = dates.map( date => date.split("/").join("-"));

console.log(formattedDates); //["2019-03-04", "2019-03-08", "2019-03-12", "2019-03-15"]
Razana N.
  • 70
  • 5