繁体   English   中英

我如何在 JavaScript/Node.JS 中解析基于时间的标记?

[英]How can I parse time based tokens in JavaScript/Node.JS?

我目前正在尝试创建一个 Discord 机器人,它会执行临时禁止,并且在大多数情况下我知道如何处理它。 唯一的问题是我无法弄清楚如何使用3w/2w/1y/etc之类的参数转换为新时间来创建计时器。 我已经在谷歌上四处搜寻以找到答案,但我什至找不到关于如何完成此任务的任何提示或技巧,也许你们可以为我指明正确的方向。

我会使用正则表达式来解析参数,然后 map 以毫秒为单位的日期:

const mapping = {
  w: 7 * 24 * 60 * 60 * 1000,
  d: 24 * 60 * 60 * 1000,
  // whatever other units you want
};

const toDate = (string) => {
  const match = string.match(/(?<number>[0-9]*)(?<unit>[a-z]*)/);
  if (match) {
    const {number, unit} = match.groups;
    const offset = number * mapping[unit];
    return new Date(Date.now() + offset);
  }
}

例子:

> toDate('3w')
2020-09-08T19:04:15.743Z
> toDate('2d')
2020-08-20T19:04:20.622Z

您可以将参数转换为毫秒,记录当前Date.now()并检查与具有特定更新率的新Date.now()的差异。

如果时间差较小,则该用户仍被禁言,否则该用户将被解禁。

您可以使用date-fns libaray
npm install date-fns

然后使用格式距离 function

formatDistance( new Date(1986, 3, 4, 11, 32, 0), new Date(1986, 3, 4, 10, 32, 0), { addSuffix: true } ) //=> 'in about 1 hour'

要转换该格式,请将hdwmy替换为x<number of seconds> ,然后将其拆分,然后将第一个乘以第二个,得到以秒为单位的总和。

假设您不想使用图书馆。 (这可能更健壮)。

下面是一些测试,您显然需要添加验证,否则可能会出现NaN

 const shortSinceToSeconds = input => { var p = input.replace('h', 'x3600').replace('d', 'x86400').replace('w', 'x604800').replace('m', 'x2.628e+6').replace('y', 'x3.154e+7').split('x') return (p[0] || 0) * (p[1] || 0) } const test = [ '1h', '13h', '1d', '100d', '1w', '100w', '2m', '1y' ] // for (let i of test) { console.log(`${i} = ${shortSinceToSeconds(i)} seconds`) }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM