我试图显示daterangepicker范围内的最近4年,而没有硬编码值。例如:如果当前年份为2020,则应显示2020年,2019年,2018年和2017年。
我尝试使用'Year '+ currentYear: [moment()....]
但这没用。
非常感谢您的帮助!
具有硬编码值的代码
$(function() {
var currentYear = moment().year(); // This Year
var currentYearStart = moment({
years: currentYear,
months: '0',
date: '1'
}); // 1st Jan this year
var currentYearEnd = moment({
years: currentYear,
months: '11',
date: '31'
}); // 31st Dec this year
var start = moment().subtract(29, 'days'); // Subtract 29 days from today
var end = moment(); // Today
function cb(start, end) {
$('#reportrange span').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY'));
}
$('#reportrange').daterangepicker({
startDate: start,
endDate: end,
ranges: {
'Today': [moment(), moment()],
'Last 30 Days': [moment().subtract(29, 'days'), moment()],
'Year 2017': [moment(currentYearStart.subtract(1, 'year')), moment(currentYearEnd.subtract(1, 'year'))],
'Year 2016': [moment(currentYearStart.subtract(1, 'year')), moment(currentYearEnd.subtract(1, 'year'))],
'Year 2015': [moment(currentYearStart.subtract(1, 'year')), moment(currentYearEnd.subtract(1, 'year'))],
'Year 2014': [moment(currentYearStart.subtract(1, 'year')), moment(currentYearEnd.subtract(1, 'year'))],
}
}, cb);
cb(start, end);
});
演示
答案 0 :(得分:1)
以防万一其他人正在寻找类似的答案,我使用下面的代码解决了这个问题。
var dateRange = {};
dateRange["Today"] = [moment(), moment()];
dateRange["Last 30 Days"] = [moment().subtract(29, 'days'), moment()];
dateRange["Year " + (currentYear - 1)] = [moment(currentYearStart.subtract(1, "year")), moment(currentYearEnd.subtract(1, "year"))]; // Year 2017
dateRange["Year " + (currentYear - 2)] = [moment(currentYearStart.subtract(1, "year")), moment(currentYearEnd.subtract(1, "year"))]; // Year 2016
dateRange["Year " + (currentYear - 3)] = [moment(currentYearStart.subtract(1, "year")), moment(currentYearEnd.subtract(1, "year"))]; // Year 2015
dateRange["Year " + (currentYear - 4)] = [moment(currentYearStart.subtract(1, "year")), moment(currentYearEnd.subtract(1, "year"))]; // Year 2014
$('#reportrange').daterangepicker({
startDate: start,
endDate: end,
ranges: dateRange
}, cb);
参考:
JavaScript set object key by variable
演示: