Necesito calcular la diferencia en días entre dos fechas.
Al final necesito saber si una fecha determinada ha expirado.
Pero no puedo encontrar una solución.
el campo expiredAt, es de tipo datetime
Servicio.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;Como sugirió @Athul Joy , debe usar Moment.js.
Primero instale el momento desde npm usando npm i moment .
Momento de importación:
import moment from 'moment';En su otra condición:
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);¿Qué hay de probar Moment.js ( https://momentjs.com/ ). Momen.js proporciona funciones predefinidas para comparar fechas
Creo que el problema es que está comparando un tipo de cadena con un tipo de fecha. Si convierte "expiredAt" a la fecha, funcionará
if (new Date(expiredAt) <= today) throw new AppError("EXPIRED", 401);