'MERN format date to month, day, year with data from nodejs server
I have a nodejs server that is fetching some data from MongoDb for a react app. When I fetch this data my 'created' value is stored as 2022-02-08T03:27:17.318Z. My question is, How and where do I reformat this to the Month, day, year. Im pretty sure I need to keep my date as this format when storing in db, but I want my user to see 02/08/2022.
here is my Node.js function for listFiles, this has the created value that needs to be changed
const listFiles = async (req, res) => {
try {
let files = await Files.find({_user: req.user.id}).select('file_name contacts duplicates failed created')
//console.log(created) ----> 2022-02-08T03:27:17.318Z
//I want 02/08/2022 do I do this in this function? or do I do this in React?
res.json(files)
} catch (err) {
return res.status(400).json({
error: dbErrorHandler.getErrorMessage(err)
})
}
}
Here is the React Action creator
export const listFiles = () => {
return async function(dispatch) {
await
axios({
url:"http://localhost:5000/files/create",
method:"GET",
withCredentials: true
}).then( res => dispatch({type: LIST_FILES, payload: res.data}))
}
}
Here is the reducer in frontend React app
import { LIST_FILES } from '../actions/types';
export default function (state = [], action) {
switch (action.type) {
case LIST_FILES:
return action.payload
default:
return state;
}
}
Solution 1:[1]
My Solution was install a library called react-moment. so npm install react-moment in frontend, and once I fetch data to frontend I can use something like this
import React from 'react'
import Moment from 'react-moment'
const Component = () => {
const createdFormatter = (rowData) => {
const {created} = rowData.row.original // getting data from react-table
return (
<Media tag={Flex} align="center">
<Media body className="ml-2">
// add this <Moment /> component and it formats date for me in React.
<h5 className="mb-0 fs--1 mt-2"><Moment format="MM/DD/YYYY"
date={created}/></h5>
</Media>
</Media>
)};
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
