Reputation: 2947
I have the following code
import React from "react";
import "./styles.css";
export default function App() {
const posts = [
{
displayDate: "2020-12-29T00:00:00.000Z"
},
{
displayDate: "2020-12-28T00:00:00.000Z"
},
{
displayDate: "2020-12-27T00:00:00.000Z"
}
];
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
{posts.map((post) => (
<p>{post.displayDate}</p>
))}
</div>
);
}
I would like to convert the time to something like 2020.12.29
as in the following
let today = new Date("2020-12-29T03:00:00.000Z");
let year = today.getFullYear();
let month = today.getMonth() + 1;
let day = today.getDate();
console.log(year + '.' + month + '.' + day)
How would I organize my code to map my dates in the above format?
My codesandbox
Upvotes: 0
Views: 267
Reputation: 10655
Working App: Codesandbox
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
{posts.map((post) => {
const date = new Date(post.displayDate);
return (
<p key={date.toString()}>
{date.getFullYear()}. {date.getMonth() + 1}. {date.getDate()}
</p>
);
})}
</div>
);
Upvotes: 1
Reputation: 118
You can try this line of code. Please let me know if this is what you want.
<p>{new Date(post.displayDate).toLocaleDateString()}</p>
Upvotes: 0
Reputation: 3856
Why not use DateTimeFormat? A running example: https://codesandbox.io/s/convert-time-forked-ru2n1
import React from "react";
import "./styles.css";
const formatDate = (date) => {
const d = new Date(date);
const ye = new Intl.DateTimeFormat("en", { year: "numeric" }).format(d);
const mo = new Intl.DateTimeFormat("en", { month: "numeric" }).format(d);
const da = new Intl.DateTimeFormat("en", { day: "2-digit" }).format(d);
return `${ye}.${mo}.${da}`;
};
export default function App() {
const posts = [
{
displayDate: "2020-12-29T00:00:00.000Z"
},
{
displayDate: "2020-12-28T00:00:00.000Z"
},
{
displayDate: "2020-12-27T00:00:00.000Z"
}
];
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
{posts.map((post) => (
<p>{formatDate(post.displayDate)}</p>
))}
</div>
);
}
Upvotes: 0
Reputation: 8751
Make convert()
method and use it inside JSX.
import React from "react";
import "./styles.css";
export default function App() {
const posts = [
{
displayDate: "2020-12-29T00:00:00.000Z"
},
{
displayDate: "2020-12-28T00:00:00.000Z"
},
{
displayDate: "2020-12-27T00:00:00.000Z"
}
];
const convert = (inputDate) => {
let date = new Date(inputDate);
let year = date.getFullYear();
let month = date.getMonth() + 1;
let day = date.getDate();
return year + '.' + month + '.' + day;
}
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
{posts.map((post) => (
<p>{convert(post.displayDate)}</p>
))}
</div>
);
}
Upvotes: 2