【发布时间】:2023-01-23 12:37:46
【问题描述】:
我正在尝试格式化 React 组件内的日期,它显示为“2022-09-26T04:46:11.629Z”,但我希望它采用 MM/DD/YYYY 格式。我应该修改 mongodb 还是只修改前端?有人可以帮我吗?我使用了 Date() 并且它有效但我的数据库停止工作。我在做全栈。
这是我的代码:
import React, { useContext, useState } from 'react';
import PostsContext from '../contexts/PostsContext';
import { Link } from "react-router-dom";
import '../App.css'
import UserContext from '../contexts/UserContext';
function PostsList(props) {
let { deletePosts } = useContext(PostsContext);
let users = useContext(UserContext);
return (
<PostsContext.Consumer>
{
({ posts }) => {
return <div>
<h3>Welcome back, "User's name"</h3>
<a href="/posts/new"><button>Add New Post</button></a>
<div>
{posts.map((c) => {
console.log(posts)
return (
<div className='posts_list'>
<div key={c._id}>
</div>
<div className='posts_text'>
<h2>{c.name}</h2>
</div>
<div className='list'>
<Link to={`/edit/${c._id}`}>
<button>Edit</button>
</Link>
<button onClick={() => { deletePosts(c._id)}}>Delete</button>
<p>Tweet created on: {c.createdAt}</p>
</div>
</div>
)
})}
</div>
</div>
}
}
</PostsContext.Consumer>
);
}
export default PostsList;
我找到了问题的答案:
var date = new Date('2010-10-11T00:00:00+05:30'); alert(((date.getMonth() > 8) ? (date.getMonth() + 1) : ('0' + (date.getMonth() + 1))) + '/' + ((date.getDate( ) > 9) ? date.getDate() : ('0' + date.getDate())) + '/' + date.getFullYear())
【问题讨论】:
-
@AndyRay 老实说不,因为我不想创建另一个变量,我正在从数据库中检索信息,我想以不同的格式呈现它。
-
<p>Tweet 创建于:{c.createdAt}</p> 这就是我遇到的问题。
-
{formatDate(c.createdAt)}并创建像重复问题所说的那样格式化日期的函数
标签: reactjs