Javascript 如何使用过滤器检查对象是否在日期范围内?
我试图检查当前筛选对象是否属于日期范围,并基于数据返回布尔值,如果它的数据不在日期范围内,则应筛选出该对象。下面的代码总是返回数据。你知道实现这项任务的错误或正确方法是什么吗 梅因酒店Javascript 如何使用过滤器检查对象是否在日期范围内?,javascript,angular,typescript,date-range,Javascript,Angular,Typescript,Date Range,我试图检查当前筛选对象是否属于日期范围,并基于数据返回布尔值,如果它的数据不在日期范围内,则应筛选出该对象。下面的代码总是返回数据。你知道实现这项任务的错误或正确方法是什么吗 梅因酒店 function mapResponse() { const _startDate = "2018-12-15"; const _endDate = "2019-01-15"; _startDate = moment.utc(_startDate || twentyfourMonthsA
function mapResponse() {
const _startDate = "2018-12-15";
const _endDate = "2019-01-15";
_startDate = moment.utc(_startDate || twentyfourMonthsAgo, ["YYYY-MM-DD", "MM-DD-YYYY", "MM/DD/YYYY"]).format("YYYY-MM-DD");
_endDate = moment.utc(_endDate || today, ["YYYY-MM-DD", "MM-DD-YYYY", "MM/DD/YYYY"]).format("MM/DD/YYYY");
const response = [
{
rxNumber: "15139",
rxIssueDate: "",
fillDate: "2019-01-03",
quantityRemaining: "3",
prescribedNoOfRefills: "3",
currentFillNumber: "0"
},
{
rxNumber: "16131",
rxIssueDate: "",
fillDate: "2019-12-03",
quantityRemaining: "3",
prescribedNoOfRefills: "3",
currentFillNumber: "0"
}
]
response = response.filter(
function renameSpecialtyAttributesToPBM(specialtyRx: any) {
const mappedRx = specialtyRx as Partial < any > ;
const dateFilter = checkDateRange(_startDate, _endDate, specialtyRx.fillDate);
if (!dateFilter) {
return false;
}
mappedRx.fillDate = specialtyRx.fillDate;
mappedRx.refillEligible = !!mappedRx.refillStatusText;
mappedRx.renewEligible = !!specialtyRenewStatus;
return true;
});
}
return response;
}
将日期字符串转换为实际的日期对象。然后在这些日期执行getTime以获取unix时间戳编号。现在,您应该能够计算其中一个日期是否介于开始日期和结束日期之间看起来您正在将字符串日期传递给check dates函数,并将其与小于/大于运算符进行比较,这就是问题所在 Moment或更新的Luxon有非常实用的日期比较方法,但是如果你想用老式的方法,你可以这样做:
checkDateRange(startDateString: string, endDateString: string, fillDateString: string): boolean {
const startDate = new Date(startDateString).getTime();
const endDate = new Date(endDateString).getTime();
const fillDate = new Date(fillDateString).getTime();
if (fillDate > startDate && fillDate < endDate) {
return true;
}
return false;
}
我更新了我的问题,我实际上使用了时间来格式化日期,你能帮我比较一下时间吗?好的,谢谢,我的fillDate也是utc时间,所以我只需要在checkDateRange方法中返回return fillDate.isBetween_startDate,_endDate
response = [
{
rxNumber: "15139",
rxIssueDate: "",
fillDate: "2019-01-03",
quantityRemaining: "3",
prescribedNoOfRefills: "3",
currentFillNumber: "0"
}]
checkDateRange(startDateString: string, endDateString: string, fillDateString: string): boolean {
const startDate = new Date(startDateString).getTime();
const endDate = new Date(endDateString).getTime();
const fillDate = new Date(fillDateString).getTime();
if (fillDate > startDate && fillDate < endDate) {
return true;
}
return false;
}
const fillDate = moment(fillDateString).utc();
return fillDate.isBetween(_startDate, _endDate);