Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
like image 510
Wagner Fillio Avatar asked Jul 19 '26 17:07

Wagner Fillio


1 Answers

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);
like image 65
Zunayed Shahriar Avatar answered Jul 22 '26 05:07

Zunayed Shahriar