我有一个充满不同日子的数组:
ngOnInit() {
this.merchantService.getList().subscribe(res => {
console.log("The response is", res);
});
}
我如何检测到距今天最近的日子是哪一天?
我的当前状态可以检测到,如果明天是数组的一部分,但是我不知道如何在明天不存在的情况下获得最近的一天。
let days = ["2018-09-02", "2018-10-06", "2018-10-12", "2018-10-24", "2018-11-02", "2018-11-04"];
答案 0 :(得分:1)
假设数组已排序,则可以执行以下操作:
let days = ["2018-09-02", "2018-10-06", "2018-10-12", "2018-10-24", "2018-11-02", "2018-11-04"];
let today = moment().format('YYYY-MM-DD');
console.log(days.find(d => d > today));
<script src="https://cdn.jsdelivr.net/npm/moment@2.19.3/moment.min.js"></script>
答案 1 :(得分:1)
一种可能性是从当前日期中减去每个日期,并查看距正数天数最少的日期。
示例:
let days = ["2018-09-02", "2018-10-06", "2018-10-12", "2018-10-30", "2018-11-02", "2018-11-04", "2019-01-01"];
let curDay = moment().format('YYYY-MM-DD');
let closestDay;
let closestDiff;
for (let i = 0; i < days.length; i++) {
let diff = moment(days[i]).diff(curDay, 'days');
if(diff > 0){
if(closestDiff === undefined) {
closestDay = days[i];
closestDiff = diff;
} else if(diff < closestDiff) {
closestDay = days[i];
closestDiff = diff;
}
}
}
if(closestDay === undefined) closestDay = "no days found in the future";
document.getElementById("closest-future").innerHTML = closestDay;
<!DOCTYPE html>
<html>
<head>
<script data-require="moment.js@2.14.1" data-semver="2.14.1" src="https://npmcdn.com/moment@2.14.1"></script>
</head>
<body>
<div>Shortest date in the future is: <span id='closest-future'></span></div>
</body>
</html>