我具有确定两个日期是否重叠的功能。当日期集在同一年时,它可以正常工作,如果有重叠,则返回true。如果其中一个日期来自上一年,则比较无法检测到重叠。
例如:
var obj = { startDate1: "02/01/2020",
endDate1: "03/01/2020",
startDate2:"02/05/2020",
endDate2:"02/15/2020" }
使用:
if ((obj.endDate1 >= obj.startDate2 && obj.startDate1 <= obj.endDate2) ||
(obj.endDate2 >= obj.startDate1 && obj.startDate2 <= obj.endDate1)) {
}
由于日期重叠,因此返回true。
但是,当startDate1在不同的年份(2019年)时,就像这样:
var obj = { startDate1: "12/01/2019",
endDate1: "03/01/2020",
startDate2:"02/05/2020",
endDate2:"02/15/2020" }
即使startDate1和endDate1实际上与startDate2和endDate2重叠,上面的表达式也无法检测到重叠。
我曾尝试使用moment和regex格式化日期,但无济于事。有什么想法我做错了吗?
const obj = {
startDate1: moment(new Date(value.startDate)).format("MM/DD/YYYY"),
endDate1: moment(new Date(value.endDate)).format("MM/DD/YYYY"),
startDate2: moment(new Date(startDate)).format("MM/DD/YYYY"),
endDate2: moment(new Date(endDate)).format("MM/DD/YYYY")
};
我要传递给新Date的值是iso日期字符串。
很抱歉造成混乱。
我只是使用本地JS Date.parse转换了日期。
const obj = {
certStart: Date.parse(value.startDate),
certEnd: Date.parse(value.endDate),
startDate: Date.parse(startDate),
endDate: Date.parse(endDate) };
答案 0 :(得分:2)
jmp
var obj = {
startDate1: "02/01/2020",
endDate1: "03/01/2020",
startDate2:"02/05/2020",
endDate2:"02/15/2020"
};
// Create a clone of obj object and convert values to timestamp.
var $dates = {};
$dates.startDate1 = new Date(obj.startDate1).getTime();
$dates.startDate2 = new Date(obj.startDate2).getTime();
$dates.endDate1 = new Date(obj.endDate1).getTime();
$dates.endDate2 = new Date(obj.endDate2).getTime();
答案 1 :(得分:1)
使用新的Date()或moment.js创建和处理日期。
var obj = { startDate1: moment("12/01/2019"),
endDate1: moment("03/01/2020"),
startDate2:moment("02/05/2020"),
endDate2:moment("02/15/2020")}
和矩函数操作日期
答案 2 :(得分:1)
将日期字符串解析为Date
,然后以数字形式获取其值:
const [m, d, y] = dateStr.split('/').map(Number)
// month is 0-indexed, whereas year and day are 1-indexed
const dateVal = new Date(y, m - 1, d).valueOf()
然后,您可以轻松地将它们与>
,<
等进行比较。
答案 3 :(得分:1)
尽管有标签,但似乎并没有真正使用momentjs格式化日期-除非您没有共享某些代码。看起来您好像在进行字符串比较。对于一般的日期比较,我建议阅读相关内容:Compare two dates with JavaScript
日期的相关MDN:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
别忘了参考一下moment.js文档:https://momentjs.com/docs/
编辑:如前所述,您正在使用.format()
,它返回显示字符串https://momentjs.com/docs/#/displaying/format/-因此您仍在比较字符串而不是日期。
您可能想结帐isBetween
:https://momentjs.com/docs/#/query/is-between/
答案 4 :(得分:1)
如果日期字符串为YYYY/MM/DD
格式,则字符串比较将起作用。
var obj = {
startDate1: "2019/12/01",
endDate1: "2020/03/01",
startDate2: "2020/02/05",
endDate2: "2020/02/15"
}
// this will work
if ((obj.endDate1 >= obj.startDate2 && obj.startDate1 <= obj.endDate2) ||
(obj.endDate2 >= obj.startDate1 && obj.startDate2 <= obj.endDate1)) {
console.log('overlap detected')
}