javascript - 在某些月份停止增加和减少月份
问题描述
目前我在一个窗口中显示 6 个月(从 2019 年 11 月到 2019 年 4 月)。用户可以转到上一个/过去 12 个月(直到 2018 年 11 月),并且可以再前进一个月(2019 年 5 月)。用户可以转到前几个月,也可以转到未来几个月,但我需要限制它。
months: any[] = [];
date = new Date();
month = this.date.getMonth();
year = this.date.getFullYear()
ngOnInit() {
this.getMonths(this.year, this.month);
}
getMonths(year:number, month:number) {
this.months = [];
for (let i = 0; i < 6; i++) {
this.months.push(new Date(year, month++));
}
}
getNextData() {
this.month++;
this.getMonths(this.year, this.month);
}
getPreviousData(){
this.month--;
this.getMonths(this.year, this.month);
}
解决方案
我认为以下内容可以帮助您。我重写了你的一些函数并引入了一个辅助函数,用于设计以月表示的日期之间的差异。(因此,如果两个日期相隔一年,则此函数将返回 12)。
然后,您可以根据它们之间的差异比较两个日期。
我还添加了两个值,this.currMonth
以便this.currYear
您可以充分比较它this.month
的this.year
原始值。这样想,如果要检查 ifthis.month
是否大于以前,则无法检查 if,this.month > this.month + 1
因为显然this.month
不大于自身加一。而且,如果您增加它,您将重新分配该值,并且您将永远无法与this.month
比自身大的值进行比较。this.currMonth
并且是恒定的,因此当您确定是否增加/减少时this.currYear
,它们总是可以作为比较的好项目this.year
。this.month
这些函数还决定了年份应该何时改变。例如,如果您返回一个月(从 1 月到 12 月),则需要将年份从 2019 年更新到 2018 年。此外,如果月份为 0(1 月),则不能递减它,因为您将得到 -1,不能用作日期比较的月份。您需要将日期更改为 11。相反,如果您从 12 月递增到 1 月,则需要将this.year
2018 年更改为 2019 年,而不是递增this.month
(这将给您 13-不是有效月份),您需要将其赋值为 0。
months: any[] = [];
date = new Date();
currMonth = this.date.getMonth();
month = this.date.getMonth();
currYear = this.date.getFullYear();
year = this.date.getFullYear();
ngOnInit() {
this.getMonths(this.year, this.month);
}
getMonths(year:number, month:number) {
this.months = [];
for (let i = 0; i < 6; i++) {
this.months.push(new Date(year, month++));
}
}
getNextData() {
var d1 = new Date(this.currYear, this.currMonth)
var d2 = new Date(this.year , this.month + 1)
var diff = this.diff_months(d2, d1)
if (diff <= 1){
if (this.month === 11){
this.month = 0
this.year++
} else {
this.month++
}
}
}
getPreviousData(){
var m = this.month - 1
var d1 = new Date(this.currYear, this.currMonth)
if (this.month === 0){
var d2 = new Date(this.year-1, 11)
} else {
var d2 = new Date(this.year, m)
}
var diff = this.diff_months(d1, d2)
if (diff <= 12){
if (m < 0){
this.month = 11
this.year--
} else {
this.month--
}
}
}
diff_months = (dt2, dt1) => {
var diff =(dt2.getTime() - dt1.getTime()) / 1000;
diff /= (60 * 60 * 24 * 7 * 4);
return Math.abs(Math.round(diff));
}
推荐阅读
- javascript - 将索引与字符串的差异匹配
- python - 自版本 2.0.0 以来散景图已损坏
- html - 只有 CSS 的响应式步进器
- java - 我得到 org.json.JSONException: No value for an item ,它存在于我的 json 数组中
- r - 如何将数据集转换为特定类型的矩阵?(RStudio)
- scala - 在scala中使用_._2时如何在过滤谓词中使用OR运算符
- vba - 导出到 CSV - 标题为 TEXT 而不是 GENERAL
- android - java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“int android.view.View.getImportantForAccessibility()”)
- colorbar - 如何将水平颜色条的标签放在matplotlib的颜色条下方?
- javascript - 在图片中写入实时文本(在图片中实时渲染文本)