我需要计算两个日期之间的天差。
最后,我需要知道某个日期是否已经过期。
但我想不出解决办法。
expiredAt字段是日期时间类型。
Service.ts
import CheckLicenses from "../../helpers/CheckLicenses";
await CheckLicenses("valor");CheckLicenses.ts
import License from "../models/License";
import AppError from "../errors/AppError";
import { logger } from "../utils/logger";
const CheckLicenses = async (company: string): Promise<boolean> => {
const license = await License.findOne({
where: { company }
});
if (!license) {
throw new AppError("ERR_NO_LICENCE_FOUND", 404);
} else {
const { expiredAt } = license;
const today = new Date();
if (expiredAt <= today) throw new AppError("EXPIRED", 401);
}
return true;
};
export default CheckLicenses;发布于 2021-03-05 07:52:43
我认为问题在于,您正在比较字符串类型和日期类型。如果您将"expiredAt“转换为”日期“,那么它将工作。
if (new Date(expiredAt) <= today) throw new AppError("EXPIRED", 401);

发布于 2021-03-05 05:06:40
正如@阿图尔Joy建议你应该使用Moment.js。
第一次安装力矩从npm使用npm i moment。
重要时刻:
import moment from 'moment';在你的其他情况下:
const expiredMoment = moment(expiredAt); //Cast as moment date
const currentMoment = moment(); //current moment date
if (currentMoment.diff(expiredMoment, 'days') > 0) throw new AppError("EXPIRED", 401);发布于 2021-03-05 03:56:51
尝试Moment.js (https://momentjs.com/)怎么样?Momen.js提供了用于比较日期的预定义函数
https://stackoverflow.com/questions/66486473
复制相似问题