简体   繁体   English

如何从实时中减去数据库时间

[英]how to subtract db time from real time

I have this:我有这个:

let minute = timeSplit[0];
let today = new Date();
if (Math.abs(today.getMinutes() - Number(minute)) <= 5) {
  client.messages.create(
    {
      to: userPhoneNumber,
      from: "12055578708",
      body:
        "hello " +
        userNameString +
        ", \nYour training session just finished with " +
        trainerNameString
    },
    function (err, data) {
      if (err) {
        console.log("err: " + err);
      }
      console.log(data);
    }
  );
} else {
  console.log("not working");
}

what it does is gets the current minute (ex. 54th minute of the hour), and subtract it from the minute that is in my database.它的作用是获取当前分钟(例如一小时的第 54 分钟),并从我的数据库中的minute中减去它。 If my db minute is within 5 minutes of the current minute, then do the next part.如果我的 db 分钟在当前分钟的 5 分钟内,则执行下一部分。

However, in my db is both minute and hour .但是,在我的数据库中是minutehour i need to check if the time in my db is within 5 minutes of the current time.我需要检查我的数据库中的时间是否在当前时间的 5 分钟内。 minute and hour are both just string values. minutehour都只是字符串值。 How can i do this?我怎样才能做到这一点?

You have the hour and the minute and you need to check whether that is within 5 minutes of the current time.你有小时和分钟,你需要检查它是否在当前时间的 5 分钟内。

What you can do is build a date object for the same day, but using the time you have stored.您可以做的是为同一天构建一个日期对象,但使用您存储的时间。 So, if you have your minute and hour you want to compare, then you can do this:因此,如果您想比较分钟和小时,则可以执行以下操作:

const today = new Date();
const myTime = new Date(today.getFullYear(), today.getMonth(), today.getDay(), hour, minute);

Now you have two date objects that you can compare.现在您有两个可以比较的日期对象。 When you subtract one from the other, the result will be in milliseconds, so you need to do some work to convert that to minutes.当您从另一个中减去一个时,结果将以毫秒为单位,因此您需要做一些工作将其转换为分钟。 In this case we divide by 1000 to get seconds and then divide by 60 to get minutes.在这种情况下,我们除以 1000 得到秒,然后除以 60 得到分钟。 Then you apply the absolute function and check if it is less than 5.然后应用绝对函数并检查它是否小于 5。

const difference = Math.abs((today - myTime) / 1000 / 60);
if (difference <= 5) {
  // send message
} else {
  // don't send the message now
}

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

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