const enum DayType {
OneYear = 'ONE-YEAR',
OneMonth = 'ONE-MONTH',
SevenDay = 'SEVEN-DAY'
}
getSearchParams = () => {
const { currentType } = this.state;
const today = new Date();
let startTime;
if (currentType === DayType.OneYear) {
//一年前
const yearDate = new Date(today);
yearDate.setFullYear(yearDate.getFullYear() - 1);
startTime = dateFormat('YYYY-mm-dd HH:MM:SS', yearDate);
} else if (currentType === DayType.OneMonth) {
//一月前
const monthDate = new Date(today);
monthDate.setMonth(monthDate.getMonth() - 1);
startTime = dateFormat('YYYY-mm-dd HH:MM:SS', monthDate);
} else if (currentType === DayType.SevenDay) {
//7天前
const dayDate = new Date(today);
dayDate.setDate(dayDate.getDate() - 7);
startTime = dateFormat('YYYY-mm-dd HH:MM:SS', dayDate);
}
return {
startTime,
endTime: dateFormat('YYYY-mm-dd HH:MM:SS', today)
};
};
不好意思,又来更新了,简化后的代码
const enum DayType {
OneYear = 'ONE-YEAR',
OneMonth = 'ONE-MONTH',
SevenDay = 'SEVEN-DAY'
}
getSearchParams = () => {
const { currentType } = this.state;
const format = 'YYYY-mm-dd';
//开始时间
const startDate = new Date();
if (currentType === DayType.OneYear) {
startDate.setFullYear(startDate.getFullYear() - 1);
} else if (currentType === DayType.OneMonth) {
startDate.setMonth(startDate.getMonth() - 1);
} else if (currentType === DayType.SevenDay) {
startDate.setDate(startDate.getDate() - 7);
}
const startTime = dateFormat(format, startDate);
//结束时间
const endDate = new Date();
endDate.setDate(endDate.getDate() + 1);
const endTime = dateFormat(format, endDate);
return {
startTime,
endTime
};
};