【问题标题】:Format date using moment React使用 Moment React 格式化日期
【发布时间】:2021-02-06 09:17:25
【问题描述】:

我已经创建了** React 组件**

class Test extends Component{

state = {
    birthdate: '2020-09-20'
}

render(){
    const {birthdate} = this.state;
    const mdiffInDays = moment(moment()).diff(moment(birthdate), 'days');
    const mdiffInWeeks = moment(moment()).diff(moment(birthdate), 'weeks');

    return(
    <div className="card">
        <span>Today: {moment(moment()).format('DD MMM YYYY')}</span>
        <span>Birthdate: {birthdate}</span>
        <span>Days: {mdiffInDays}</span>
        <span>Weeks: {mdiffInWeeks}</span>           
    </div>            
    )
}}

我有两个问题:

  1. 今天 - 我怎样才能使用23-Oct-2020 而不是"PL" region?
  2. Birthdate 呈现为:YYYY-MM-DD。如何将其更改为 display "DD-MM-YYY"?

我正在学习 React 并尝试现在玩日期。

【问题讨论】:

  • 如果您想要不同的格式,为什么要使用.format('DD MMM YYYY') 或'2020-09-20'?
  • 当我更改为 '20-09-2020' 时,进入 mdiffInDays 我得到像 -45 这样的值

标签: reactjs react-native date momentjs moment-timezone


【解决方案1】:

const birthdate =  '2020-09-20'
const date = new Date(birthdate)
const options = {
  year: "numeric",
  month: "short",
  day: "numeric",
};
console.log(date.toLocaleDateString("pl", options));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-17
    • 1970-01-01
    • 2018-08-30
    • 2018-12-08
    • 2019-10-29
    相关资源
    最近更新 更多