Convert timestamp to date in React
My blog page is built on using Next.js and Notion, and when working on it, I had a need to convert timestamp to date.
So, I started to investigate solutions.
By default, JavaScript provides the Date object, which is perfect. It means that there is no need to load a 3rd party library.
However, when I tried to use this object in my React website, I got the following error message: Objects are not valid as a React child
.
Here is a code snippet that I used:
<p>{new Date(postTimestamp)}</p>
Solution
Since the render output may only contain React elements, strings, and numbers, I had to convert my Date object into a string to resolve the issue.
Here is an example of a working code snippet:
<p>{new Date(postTimestamp * 1000).toDateString()}</p>
Note, I've also multiplied the timestamp by 1000
to convert the value from seconds to milliseconds because JavaScript uses milliseconds internally, while normal UNIX timestamps are usually in seconds.
It is also possible to use the toLocaleString()
method to better format your date. Here is an another example of using the Date object, but with toLocaleString()
:
const savedTime = '2021-12-23T19:34:00.000Z';
const formatedDate = new Date(savedTime).toLocaleString(
"en-US",
{
month: "short",
day: "2-digit",
year: "numeric",
}
);
console.log(formatedDate); // Dec 29, 2021
Hope this tip, on how to to display date from timestamp, was helpful.