我想使用react中的next和previous按钮来确定下一个日期和上一个日期。
我尝试过通过创建两个按钮“下一个”和“上一个”按钮,但是当月份开始和结束时它无法正常工作。
这些是按钮:
<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();
}
它工作正常,但是在月底和月初它不工作。
答案 0 :(得分:1)
为获得更准确的更新,我们可以按日期值(以毫秒为单位)更改日期。考虑一下此沙箱和以下代码: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);
答案 1 :(得分:0)
const myDate = new Date()
myDate.setDate(myDate.getDate() - 1)
这会减少一天,但是建议您使用luxon之类的库作为日期