如何在聚合物上直到今天和下一个日期显示以前的日期?
我尝试了以下脚本,但它不起作用。
我只得到昨天和明天的日期,重复在控制台上。我想要以前的一天,依此类推。另外我一定不能落后于今天。
<header>
<iron-icon class="icon" icon="chevron-left" on-tap="previousDay" suffix></iron-icon>
<iron-icon class="icon" icon="chevron-right" on-tap="nextDay" suffix></iron-icon>
</header>
<br/><br/>
nextDay: function() {
var currentDay = new Date();
currentDay.setDate(currentDay.getDate() + 1);
console.log(currentDay);
},
previousDay: function () {
var currentDay = new Date();
currentDay.setDate(currentDay.getDate() - 1);
console.log(currentDay);
},
可能的解决方案是:
nextDays: function() {
var currentDay = new Date();
var nextDays = [];
for (var i = 1; i <= 30; i++) {
var newDate = new Date();
newDate.setDate(currentDay.getDate() + i);
nextDays.push(newDate);
}
// nextDays will contain the 30 next days
}
previousDays: function() {
var currentDay = new Date();
var previousDays = [];
for (var i = 1; i <= 30; i++) {
var newDate = new Date();
newDate.setDate(currentDay.getDate() - i);
previousDays.push(newDate);
}
// previousDays will contain the 30 last days
}
您可以简单地更改所需的天数(30个示例中(,然后使用阵列nextDays
和previousDays
。
您可以添加的是如今的缓存,因此您不必每次都会生成它们(尤其是在同一天(。
这是使用私有变量的简单解决方案。
var date = (() => {
var currentDay = new Date();
function previousDay() {
currentDay.setDate(currentDay.getDate() - 1);
return currentDay;
}
function nextDay() {
currentDay.setDate(currentDay.getDate() + 1);
return currentDay;
}
return { previousDay, nextDay };
})();
<button onclick="console.log(date.previousDay())">Previous day</button>
<button onclick="console.log(date.nextDay())">Next day</button>
您甚至可以缩短它,两者都可以使用相同的功能:
var date = (() => {
var currentDay = new Date(),
previousDay = () => goToDay(-1),
nextDay = () => goToDay(1);
function goToDay(n) {
currentDay.setDate(currentDay.getDate() + n);
return currentDay;
}
return { previousDay, nextDay };
})();
<button onclick="console.log(date.previousDay())">Previous day</button>
<button onclick="console.log(date.nextDay())">Next day</button>