提问者:小点点

在JavaScript中将秒转换为小时,分钟和秒


我想为我的不和机器人设置一个冷却时间,下面是代码:

    if (!cooldowns.has(command.name)) {
        cooldowns.set(command.name, new Discord.Collection());
    }
    
    const now = Date.now();
    const timestamps = cooldowns.get(command.name);
    const cooldownAmount = (command.cooldown || 3) * 1000;

    if (timestamps.has(message.author.id)) {
    const expirationTime = timestamps.get(message.author.id) + cooldownAmount;

    if (now < expirationTime) {
        const timeLeft = (expirationTime - now) % 3600 / 60
        return message.reply(`please wait ${timeLeft.toFixed(1)} Hours before reusing the \`${command.name}\` command.`);
    }
}

timestamps.set(message.author.id, now);
setTimeout(() => timestamps.delete(message.author.id), cooldownAmount);

该命令的延迟为'86400'/24小时,但输出显示36.2小时而不是24小时。 有人知道为什么吗?


共1个答案

匿名用户

对这两个日期进行子分隔将使您在ms中获得差异。 要计算小时的差异,应使用:

 const timeLeft = (expirationTime - now) / 1000 / 3600;

注意,如果您计划进行更复杂的日期运算,我建议使用MomentJS这样的库。