我有一个日期范围,假设是 2000-01-01 到 2021-06-01。我想使用 JavaScript 检查给定年份的特定月份是否在此范围内(例如,月份 = 三月和年份 = 2021)。
答案 0 :(得分:0)
创建一个可重用的函数 isDateInRange
,它接受您的三个日期字符串参数。
您可以使用所需的操作数简单地比较您的 Date Objects:
const isDateInRange = (date, from, to) => {
const d = new Date(date);
const f = new Date(from);
const t = new Date(to);
return (d >= f && d < t);
};
console.log(isDateInRange("2001-01-31", "2000-01-01", "2021-06-01")) // true
console.log(isDateInRange("2050-01-01", "2000-01-01", "2021-06-01")) // false
答案 1 :(得分:0)
这是按照您的要求传递月份和年份(不是日期)的解决方案。
const lowerRange = new Date('2000-01-01');
const upperRange = new Date('2021-06-01');
// If month and year are numbers
const monthYearInRange = (year, month) => {
if (typeof month !== 'number') throw new Error('Month should be number');
if (typeof year !== 'number') throw new Error('Year should be number');
// We do this to make sure it is 2 chars.
const mth = month < 10 ? `0${month}` : month;
// Set it to first of the month
const checkVal = new Date(`${year}-${mth}-01`);
if (isNaN(checkVal)) throw new Error(`Year: ${year} and Month: ${month} are not valid.`);
return checkVal <= upperRange && checkVal >= lowerRange;
}
console.log(monthYearInRange(2000, 2)); // true
console.log(monthYearInRange(2030, 2)); // false
console.log(monthYearInRange(2021, 6)); // true
console.log(monthYearInRange(2021, 10)); // false
请注意此解决方案 - 因为最终我们将年/月转换为日期,因此在执行此操作时,我们必须使用 ISO 格式 YYYY-MM-DD
实例化日期。如果 checkVal
被实例化为单个字符的月份(1
而不是 01
),它在大多数情况下仍然可以工作 - 但是你会遇到边缘情况,因为 {{1 }} 构造函数会将时区值添加到日期。
更新:添加了 NaN 检查 - 每个 @RobG
答案 2 :(得分:0)
I tried the following approach and it worked:
function isBetween(n, a, b) {
return (n - a) * (n - b) <= 0
}
var startDate = '2021-03-15';
var endDate = '2021-06-01';
var checkFor = '2021-05-31';
D_1 = startDate.split("-");
D_2 = endDate.split("-");
D_3 = checkFor.split("-");
//console.log(D_1+" "+D_2+" "+D_3);
var startNumber = D_1[0]*100 + D_1[1];
var endNumber = D_2[0]*100 + D_2[1];
var checkNumber = D_3[0]*100 + D_3[1];
var check = isBetween(checkNumber, startNumber, endNumber);
console.log(check);