[英]How can I use date type using map function in React?
I've just started studying React.我刚刚开始学习 React。
I'm using map function to use data.我正在使用 map function 来使用数据。
Here's my code.这是我的代码。
{dailynoteList.map((val) => {
return (
<div key={val.index} className="dailybox">
//<div className="valSubject">
//<div className="subjectText">{val.subject}</div>
//</div>
<div className="contentDate">
<div className="valDate">{val.date}</div>
</div>
</div>
)
})}
And the result of "{val.date}" is like this.而“{val.date}”的结果是这样的。
I want to use only month and date like "8/8" or "August 8".我只想使用月份和日期,例如“8/8”或“8 月 8 日”。
How can I use {val.date}?如何使用 {val.date}?
Just utilize the Date
constructor and the method toDateString
to format it.只需使用Date
构造函数和toDateString
方法对其进行格式化。
<div className="valDate">{new Date(val.date).toDateString()}</div>
You may also use package moment
for this and it provides more formatting, but the library is quite heavy.您也可以为此使用 package moment
,它提供了更多格式,但库非常重。
install安装
npm install moment --save
import to your component导入到您的组件
import moment from 'moment'
change改变
<div className="valDate">{new Date(val.date).toDateString()}</div>
to到
<div className="valDate">{moment(val.date).format('LL')}</div>
This is not the right question, it should be How to get year/month/day from a date object?
这不是正确的问题,应该是How to get year/month/day from a date object?
anyway JS only you can反正JS只有你可以
new Date(val.date).toLocaleDateString() // thats will return "8/8/2021" // or you can new Date(val.date).toLocaleDateString().slice(0,3) // thats will return 8/8
Im suggestion that you play a bit with Date constructor, and read about it JavaScript Date objects我建议你玩一下 Date 构造函数,并阅读它JavaScript Date objects
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.