Home > Mobile >  how to change date format to isostring
how to change date format to isostring

Time:08-14

I have array of object and I would like to change date format for both date.[date and dateofbirth]into iso string. I tried to use map to change date format but with no luck. how can i change date format for both dates dynamically?

//array of object
const emp = [
{ name: "John", age: 22, date: "2015-03-25", dateofbirth: "1990-03-25" },
{ name: "Peter", age: 20, date: "2015-04-23", dateofbirth: "1389-03-03" },
{ name: "Mark", age: 23, date: "2015-01-20", dateofbirth: "1970-11-03" }
];

//my code 
let modifiedArr = emp.map(function (newDate) {
return newDate.date.toISOString;
});

console.log(modifiedArr);

CodePudding user response:

Please read up on and get better understanding of the map() function from the documentation of map() function in JS.

The map() function iterates over the array and applies the specified callback on each item.

Next, you need to construct Date objects using the Date constructor. Only then can you call the toISOString() method.

//array of object
const emp = [
  { name: "John", age: 22, date: "2015-03-25", dateofbirth: "1990-03-25" },
  { name: "Peter", age: 20, date: "2015-04-23", dateofbirth: "1389-03-03" },
  { name: "Mark", age: 23, date: "2015-01-20", dateofbirth: "1970-11-03" },
];

//my code
let modifiedArr = emp.map(function (empRecord) {
  return {
    ...empRecord,
    date: new Date(empRecord.date).toISOString(),
    dateofbirth: new Date(empRecord.dateofbirth).toISOString(),
  };
});

console.log(modifiedArr);

However, I strongly recommend luxon whenever dealing with dates. Simply because the vanilla JS Date API is borked.

CodePudding user response:

toISOString() is method inside the javascript Date class, While the value of the date attribute is a string literal. Hence you will first have to get an instance of the Date class and then invoke the toISOString() function.

This can be done in the following way,

let modifiedArr = emp.map(function (item) {

  // This will create a Date object representing the given date
  const currDate = new Date(item.date);

  return currDate.toISOString;
});

CodePudding user response:

const emp = [
    {name: "John", age: 22, date: "2015-03-25", dateofbirth: "1990-03-25"},
    {name: "Peter", age: 20, date: "2015-04-23", dateofbirth: "1389-03-03"},
    {name: "Mark", age: 23, date: "2015-01-20", dateofbirth: "1970-11-03"}
];
let dateKeys = ['date', 'dateofbirth'];
var getDateInISO = function(date) {
    return new Date(date).toISOString();
}
let modifiedArr = emp.map(function (elem) {
    dateKeys.forEach(function(date) {
        elem[date] = getDateInISO(elem[date]);
    })
    return elem;
});
console.log(modifiedArr);

  • Related