首页 > 解决方案 > 无法比较午夜前后的时间

问题描述

我正在尝试比较午夜之前和之后的时间,但是在午夜之后检查失败。

我想做的是检查时间是否在晚上 11 点到早上 6 点之间。

这是我正在使用的

// Hours
const start =  23 * 60 + 0;
const end   =   6 * 60 + 0;

// Get todays date 11pm
const now = new Date();

// Check tomorrow for 6am
const nextDay = new Date(now.getTime() + 86400000); 

const time_today = now.getHours() * 60 + now.getMinutes();
const time_tomorrow = nextDay.getHours() * 60 + nextDay.getMinutes();

if (time_today >= start && time_tomorrow < end) {
    return interaction.reply({content: `You cannot do that until 6am.`, ephemeral: true})
}

标签: javascriptnode.jsdiscord.js

解决方案


既然你有now.getHours(),为什么不检查一下是不是在晚上 11 点到早上 6 点之间呢?

const hours = now.getHours();
if (hours < 6 || hours==23){
  return interaction.reply({content: `You cannot do that until 6am.`, ephemeral: true});
}

推荐阅读