gpt4 book ai didi

javascript - 如何使用 react 中的下一个和上一个按钮将日期增加和减少 1 天?

转载 作者:行者123 更新时间:2023-12-02 23:25:10 26 4
gpt4 key购买 nike

我想使用 react 中的下一个和上一个按钮来确定下一个日期和上一个日期。

我尝试创建两个按钮“下一个”和“上一个”按钮,但在月份开始和结束时它无法正常工作..

这些是按钮:

<button onClick={() => this.previousDate(this.state.selectdate)} 
>Previous</button><input type="text" name="selectdate" id="reactroot"
newdate={this.state.selectdate} value={this.state.selectdate} />
<button onClick={() => this.nextDate(this.state.selectdate)}>Next</button>

这是我获取之前日期的函数:

previousDate(datetime) {
var months_arr = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul',
'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
var getselectdate = datetime;
var date = new Date(getselectdate); //Current Date
var month = months_arr[date.getMonth()];
var year = new Date().getFullYear(); //Current Year
var day = date.getDate() - 1;
var compdataTime = month + '-' + day + '-' + year;
// now convert new date in timestamp
var datenew = new Date(compdataTime); //Current Date
var finaldate = datenew.getTime() / 1000;

console.log(finaldate)

this.setState({ selectdate: compdataTime });

this.getDetailsBydatePrevious();
}

它工作正常,但在月底​​和月初它无法工作。

最佳答案

为了获得更准确的更新,我们可以按日期值(以毫秒为单位)更改日期。考虑这个沙箱和下面的代码:https://codesandbox.io/s/gallant-euler-67w40

import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";

class App extends React.Component {
state = {
selectedDate: null
};

componentDidMount() {
this.setDate();
}

setDate = (newDate) => {
const date = newDate || new Date();
this.setState({
selectedDate:
date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate()
});
};

getPreviousDate = () => {
const { selectedDate } = this.state

const currentDayInMilli = new Date(selectedDate).getTime()
const oneDay = 1000 * 60 *60 *24
const previousDayInMilli = currentDayInMilli - oneDay
const previousDate = new Date(previousDayInMilli)

this.setDate(previousDate)

}

getNextDate = () => {
const { selectedDate } = this.state

const currentDayInMilli = new Date(selectedDate).getTime()
const oneDay = 1000 * 60 *60 *24
const nextDayInMilli = currentDayInMilli + oneDay
const nextDate = new Date(nextDayInMilli)

this.setDate(nextDate)

}

render() {
return (
<div>
<h3>Date: {this.state.selectedDate}</h3>
<button onClick={this.getPreviousDate}>Previous</button>
<button onClick={this.getNextDate}>Next</button>
</div>
);
}
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

关于javascript - 如何使用 react 中的下一个和上一个按钮将日期增加和减少 1 天?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56767514/

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