【问题标题】:Days between two dates - typescript两个日期之间的天数 - 打字稿
【发布时间】:2021-03-05 03:47:21
【问题描述】:

我需要计算两个日期之间的天数差。

最后我需要知道某个日期是否已过期。

但我想不出解决办法。

expiredAt 字段的类型为 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;

【问题讨论】:

  • expiredAt 的类型是什么?时间戳编号或日期
  • 类型为日期时间
  • 哇,新类型。让我们试试if (expiredAt.valueOf() &lt;= today.valueOf())

标签: node.js typescript


【解决方案1】:

@Athul Joy 建议您应该使用 Moment.js。

使用 npm i moment 从 npm 首次安装时刻。

导入时刻:

import moment from 'moment';

在你的 else 条件下:

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);

【讨论】:

    【解决方案2】:

    试试 Moment.js (https://momentjs.com/) 怎么样。 Momen.js 提供了预定义的函数来比较日期

    【讨论】:

      【解决方案3】:

      我认为问题在于您将字符串类型与日期类型进行比较。如果您将“expiredAt”转换为日期,那么它将起作用

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-06-14
        • 1970-01-01
        • 2013-02-05
        • 1970-01-01
        • 1970-01-01
        • 2023-02-07
        相关资源
        最近更新 更多