1.引入moment包:
yarn add moment --save
2.页面代码截取
import moment from 'moment';
constructor(props) {
super(props)
this.state = {
day: moment().format('YYYY-MM-DD'),
showDay: moment().format('MM-DD'),
}
}
// 日期切换,前后天
changeDay = (val) => {
let d = new Date(this.state.day)//当前展示日期
let s, showDay//s:年月日 showDay:月日
let oneDayTime = 24 * 60 * 60 * 1000//一天的time
if (val == 1) {
//后一天
s = moment(d.getTime() + oneDayTime).format('YYYY-MM-DD');
showDay = moment(d.getTime() + oneDayTime).format('MM-DD');
} else {
// 前一天
s = moment(d.getTime() - oneDayTime).format('YYYY-MM-DD');
showDay = moment(d.getTime() - oneDayTime).format('MM-DD');
}
this.setState({
day: s,
showDay: showDay
}, () => {
console.log('当前日期:', this.state.day)
})
}
效果图: