Home > Mobile >  Change date format in a json file
Change date format in a json file

Time:03-18

I have a JSON file with multiple entries similar to the one below

[
 {
  "timestamp": "7/8/2021",
  "parent": "/develop-life-skills/",
  "name": "Markus",
  "comment": "Lorem ipsum dola sit amet.",
  "isAuthor": false
  }
]

Would anyone advise me on how to convert the timestamp to a format of yyyy-mm-dd?

CodePudding user response:

I would take that data, throw it into a script that uses JSON.parse(data) and maps over that data to update the value accordingly. Using a library like date-fns is what I'd reach for.

import {format} from 'date-fns';

const data = [
 {
  "timestamp": "7/8/2021",
  "parent": "/develop-life-skills/",
  "name": "Markus",
  "comment": "Lorem ipsum dola sit amet.",
  "isAuthor": false
  }
];

const formattedData = JSON.parse(data).map(item => {
  const itemWithNewDateFormat = {
    ...item,
    timestamp: format(new Date(item.timestamp), 'yyyy-mm-dd')
  }

  return itemWithNewDateFormat;
});

// You could then stringify with JSON.stringify(formattedData)

CodePudding user response:

try this, if you use map funciton, it will create another array, this code updates existed one

var json=...your obj;

json.forEach((item) => {
  var arr = item.timestamp.split("/");
  item.timestamp = `${arr[2]}-${arr[0].padStart(2,"0")}-${arr[1].padStart(2,"0")}`;
});

CodePudding user response:

Try using the built-in toLocateDateString()...

let formattedDate = new Date(item.timestamp).toLocaleDateString('en-CA', { year: 'numeric', month: 'numeric', day: 'numeric' });
  • Related