Moment.js:确定是否已经过去24小时

时间:2019-12-09 04:42:31

标签: javascript node.js momentjs node-modules

非常简单,但是基本上我需要检查自用户提供特定命令以来是否已经过了24小时。 (限速1次使用/天)当他们使用该命令时,将保存并存储当前时间,所以没问题,但是当前系统仅按日期运行,检查lastDaily的日期部分小于当前日期。这会导致命令在午夜重置。

我要这样做,以便如果用户在2:25PM上的9/12/2019上运行每日命令,则他们将无法使用该命令,直到第二天的同一时间(或第二分钟)

代码

const fs = require("fs");
const moment = require("moment");
const { RichEmbed } = require("discord.js");
const { m } = require("../../botconfig.json");

module.exports = {
  config: {
    // Command Config: Hidden for space's sake.
  },

  run: async (bot, message, args) => {
    let userData = JSON.parse(fs.readFileSync("db/userdata.json", "utf8"));

    let sender = message.author;

    // Initialise missing data if needed
    if (!userData[sender.id]) { // if there is no userdata,
      userData[sender.id] = {}; // Create it as an empty object
    }
    if (!userData[sender.id].money) {
      userData[sender.id].money = 1000;
    }
    if (!userData[sender.id].lastDaily) {
      userData[sender.id].lastDaily = "";
    }

    // Save Changes to File
    fs.writeFile("db/userdata.json", JSON.stringify(userData), err => {
      if (err) console.error(err);
    });

    var cancollect = false;
    let ld = userData[sender.id].lastDaily;

    if (ld != moment().format("L")) { // MM/DD/YY
      userData[sender.id].lastDaily = moment().format("L");
      userData[sender.id].money += 500;
      // Send Success Embed
    } else {
      // Send Failure Embed
    }
    // Save Changes Again
    fs.writeFile("db/userdata.json", JSON.stringify(userData), err => {
      if (err) console.error(err);
    });
  }
};

2 个答案:

答案 0 :(得分:3)

如果您以MM/DD/YY格式存储日期,则无法检查时差。因此,为了获得时差,如果可以将其存储为"2019-12-10T10:53:53+05:30"之类的格式,则可以通过moment().format()获得当前时间戳。

您可以执行以下操作

lastDate = moment().format()
> "2019-12-09T10:53:53+05:30"

nextDay = moment(lastDate).add(1, 'days').format()
> "2019-12-10T10:53:53+05:30"

一旦获得上述格式的时间戳,就需要将日期转换为Unix格式

lastDate = moment(lastDate).valueOf()
> 1575869033000

nextDay = moment(nextDay).valueOf()
> 1575955433000

现在,您可以通过这样做来获得时间上的差异

result = moment(nextDay-lastDate).valueOf()
> 86400000 // which is =24hrs

希望这会有所帮助:)

答案 1 :(得分:0)

您可以参考以下示例来解决您的问题。

        let lastExecutionTime = Moment().utc().format(); //your last execution time
        let nextDay = Moment(lastExecutionTime).add(1,'day').utc().format(); // calculate 24 hours next to last access
        let currentTime = Moment().utc().format(); //current time
        let canExecuteNow = Moment(currentTime).isSameOrAfter(nextDay);