打字稿日期验证格式

时间:2021-06-16 08:17:41

标签: javascript typescript date

我正在为我的应用程序使用 Typescript。我在数据库中有两组数据,一组是date,一组是time。两者都需要字符串。

我在用户选择日期时发出了一个 POST 请求,并且将为用户选择该时间。我为用户的选择时间何时结束做了一个辅助函数,在这种情况下,我会在前端向他们展示一个提示

<块引用>

“您选择的时间已过期!”

我的逻辑工作正常,但我试图摆脱 Typescript 错误。

这是我的Typescript playground error

<块引用>

找不到名称“要求”。你需要为节点安装类型定义吗?试试npm i --save-dev @types/node

“字符串”类型的参数不能分配给“数字”类型的参数。

算术运算的左侧必须是“any”、“number”、“bigint”或枚举类型。

“字符串”类型的参数不能分配给“数字”类型的参数。

对象可能为“空”。

这是我的代码

const { isToday, format } = require("date-fns");

const expiredTime = (date: string, time: string) => {
  const [yyyy, mm, dd] = date.split("-");
  const d = new Date();
  d.setFullYear(yyyy);
  d.setMonth(mm - 1);
  d.setDate(dd);
  if (isToday(d)) {
    const now = d.toTimeString().match(/(\d{2}:\d{2}):.*/)[1];
    const [start, end] = time.split("-");

    return now >= start && now <= end;
  }
  return false;
};

const text = expiredTime("2021-06-16", "10:55-12:00") ? "OK" : "Expired";
console.log(text);

3 个答案:

答案 0 :(得分:1)

  1. 您应该将 yyyymmdd 解析为数字;
  2. 正则表达式的结果可以为空;

你的代码应该是

const { isToday, format } = require("date-fns");

const expiredTime = (date: string, time: string) => {
  const [yyyy, mm, dd] = date.split("-").map(parseInt);
  const d = new Date();
  d.setFullYear(yyyy);
  d.setMonth(mm - 1);
  d.setDate(dd);
  if (isToday(d)) {
    const matched = d.toTimeString().match(/(\d{2}:\d{2}):.*/);
    if (!matched){
      console.log("invalid date");
      return false;
    }
    const now = matched[1];
    const [start, end] = time.split("-");

    return now >= start && now <= end;
  }
  return false;
};

const text = expiredTime("2021-06-16", "10:55-12:00") ? "OK" : "Expired";
console.log(text);

答案 1 :(得分:0)

您发布的打字稿不完整。

  • 注意处理 Object is possibly 'null' 错误的可选链
  • 使用一元 + 运算符转换为数字 - 将映射保存到 parseInt,TS 需要日期构造函数中的整数。
  • 告诉 TS 您正在使用拆分中的字符串数组

最后我更改了日期创建。单独设置零件效率不高。这是在我还没有完全掌握你的规格的时候完成的

const { isToday, format } = require("date-fns");

const expiredTime = (date: string, time: string) => {
  const [yyyy, mm, dd]: Array<string> = date.split("-");
  const d: Date = new Date(+yyyy, +mm - 1, +dd);
  if (isToday(d)) {
    const now = d?.toTimeString()?.match(/(\d{2}:\d{2}):.*/)?.[1];
    if (now) {
      const [start, end] = time.split("-");
      return now >= start && now <= end;
    }
    return false;
  }
  return false;
};

const text = expiredTime("2021-06-16", "10:55-12:00") ? "OK" : "Expired";
console.log(text);

答案 2 :(得分:-1)

为什么它接受作为答案??它不给出任何时间输出