【问题标题】:MERN format date to month, day, year with data from nodejs serverMERN格式日期到月,日,年,数据来自nodejs服务器
【发布时间】:2022-02-10 18:01:12
【问题描述】:

我有一个 nodejs 服务器,它从 MongoDb 获取一些数据以用于反应应用程序。当我获取这些数据时,我的“创建”值存储为 2022-02-08T03:27:17.318Z。我的问题是,我如何以及在哪里将其重新格式化为月、日、年。我很确定在数据库中存储时我需要将日期保持为这种格式,但我希望我的用户看到 02/08/2022。

这是我的 ListFiles 的 Node.js 函数,它具有需要更改的创建值

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)
                    })
                }
            }

这是 React Action 创建器

 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}))
                }
        }

这是前端 React 应用中的 reducer

import { LIST_FILES } from '../actions/types';


export default function (state = [], action) {
    switch (action.type) { 
        case LIST_FILES:
            return action.payload  
            default:
            return state;
    }
}

【问题讨论】:

    标签: node.js reactjs mongodb date


    【解决方案1】:

    我的解决方案是安装一个名为 react-moment 的库。所以 npm install react-moment 在前端,一旦我将数据提取到前端,我就可以使用这样的东西

    
    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>
      )};
    
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-29
      • 1970-01-01
      • 1970-01-01
      • 2015-02-03
      • 1970-01-01
      • 1970-01-01
      • 2013-10-25
      • 1970-01-01
      相关资源
      最近更新 更多