Raz
Raz

Reputation: 319

How to convert JSON dates to Calender format?

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'].

Upvotes: 3

Views: 385

Answers (2)

lumio
lumio

Reputation: 7585

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

Upvotes: 2

Razana N.
Razana N.

Reputation: 70

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"]

Upvotes: 1

Related Questions