Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

184
Visualizações
Days between two dates - typescript

I need to calculate the difference in days between two dates.

In the end I need to know if a certain date has expired.

But I can't come up with a solution.

the expiredAt field, is of type datetime

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;
over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

As @Athul Joy suggested you should use Moment.js.

First install moment from npm using npm i moment.

Import moment:

import moment from 'moment';

At your else condition:

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);
over 4 years ago · Santiago Trujillo Relatório

0

What about trying Moment.js (https://momentjs.com/). Momen.js provides predefined functions to compare dates

over 4 years ago · Santiago Trujillo Relatório

0

I believe the problem is that you are comparing a string type with a date type. If you convert "expiredAt" to date then it will work

if (new Date(expiredAt) <= today) throw new AppError("EXPIRED", 401);

enter image description here

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda