如何在 JavaScript/Node.JS 中解析基于时间的标记?
How can I parse time based tokens in JavaScript/Node.JS?
我目前正在尝试创建一个临时禁止的 Discord 机器人,并且在大多数情况下我知道如何处理它。唯一的问题是我无法弄清楚如何使用 3w/2w/1y/etc
之类的参数转换为新时间来创建计时器。我已经爬遍了 Google 寻找答案,但我什至找不到关于如何完成这个问题的任何提示或提示,也许你们可以为我指明正确的方向。
您可以将参数转换为毫秒,记录当前 Date.now()
并检查与具有特定更新率的新 Date.now()
的差异。
如果时间差较小,则用户仍被封禁,否则解封。
你可以使用date-fns libaray
npm install date-fns
然后使用formatDistance函数
formatDistance( new Date(1986, 3, 4, 11, 32, 0), new Date(1986, 3, 4, 10, 32, 0), { addSuffix: true } ) //=> 'in about 1 hour'
我会使用正则表达式来解析参数,然后通过毫秒将其映射到日期:
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
要转换该格式,请将 h
、d
、w
、m
和 y
替换为 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`)
}
我目前正在尝试创建一个临时禁止的 Discord 机器人,并且在大多数情况下我知道如何处理它。唯一的问题是我无法弄清楚如何使用 3w/2w/1y/etc
之类的参数转换为新时间来创建计时器。我已经爬遍了 Google 寻找答案,但我什至找不到关于如何完成这个问题的任何提示或提示,也许你们可以为我指明正确的方向。
您可以将参数转换为毫秒,记录当前 Date.now()
并检查与具有特定更新率的新 Date.now()
的差异。
如果时间差较小,则用户仍被封禁,否则解封。
你可以使用date-fns libaray
npm install date-fns
然后使用formatDistance函数
formatDistance( new Date(1986, 3, 4, 11, 32, 0), new Date(1986, 3, 4, 10, 32, 0), { addSuffix: true } ) //=> 'in about 1 hour'
我会使用正则表达式来解析参数,然后通过毫秒将其映射到日期:
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
要转换该格式,请将 h
、d
、w
、m
和 y
替换为 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`)
}