gpt4 book ai didi

reactjs - 为什么这个日期总和在 react 中没有正确显示?

转载 作者:行者123 更新时间:2023-12-04 10:46:42 24 4
gpt4 key购买 nike

我有以下组件,它只是获取当前日期,为其添加一年,并应该呈现它。但它呈现出一个奇怪的数字

    import React from 'react'

class Calendario extends React.Component {
constructor(props) {
super(props);

this.state = {
birth_date : new Date(),
years_to_live: 10,
death_date: ""
};

}

componentDidMount() {
var death_date = this.state.birth_date.setFullYear(this.state.birth_date.getFullYear() + 1) //this is should result in the current date +1
this.setState({ death_date : death_date});
}

render() {
return (
<div>
<p>Hello world!</p>
<p>{this.state.death_date}</p>

</div>
)
}
}

export default Calendario;

它出于某种原因呈现
1610227797517

代替
Sat Jan 09 2021 22:21:12 GMT+0100 (Central European Standard Time)

这是什么问题?

最佳答案

由于您使用的是 javascript Date,因此您将返回一个整数日期。对象 birth_date .

您可以将其解析回日期以执行您需要的操作(格式等)

var dt = new Date(1610227797517);
console.log(dt);
// output: Sat Jan 09 2021 16:29:57 GMT-0500 (Eastern Standard Time)

但是,您应该能够在对象本身上使用格式
console.log(this.state.death_date.toDateString());
// output: Sat Jan 09 2021

关于reactjs - 为什么这个日期总和在 react 中没有正确显示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59672415/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com