How to format a date that is a value in array of objects


array1=[{description:'run', 'duration':23, date:2200-2-11, id:12},
                   {description:'fun', 'duration':3, date:2200-3-11, id:1},
                   {description:'gun', 'duration':20, date:2200-9-11, id:2},
                   {description:'yummy', 'duration':21, date:2200-10-11, id:14}];
console.log(array1);
console.log(array1[0].date)
array1.map(x => {
let dateFormatted = new Date(x.date).toDateString();
return dateFormatted;  
})
console.log(array1)
// How we can format all dates to toDateString()

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

1 Like

You are not storing the dates correctly when you create array1.

date:2200-2-11,

This is setting the date property to the number 2187 because it is treating it as 2200 minus 2 minus 11. So you’ll want to store the date as a string (keep the format you have). Then in the map you can split the date on the dash and pass the three values into a new Date object to get them nicely formatted with toDateString.

Refer to MDN’s documentation on Date for more info.

2 Likes

Thanks a lot

Bruce via The freeCodeCamp Forum <freecodecamp@discoursemail.com>, 21 Eki 2021 Per, 11:30 tarihinde şunu yazdı:

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.