比较前将时间增加一小时

Increase time by an hour before comparing

本文关键字:增加 一小时 时间 比较      更新时间:2023-09-26

我有包含军事格式时间的代码。

<div class="em" data-time="17:30">

我正在将该时间与当前时间进行比较,以确定设定的时间是否已过去。

var curDate = new Date(),
    curTime = curDate.getTime(),
    givenTm = $(this).find('.em').attr('data-time'),
    givenMs = Date.parse(curDate.toDateString() + ' ' + givenTm);
if (curTime > givenMs) {
   // time has passed
}

我需要修改我的代码,不是检查数据属性中的时间,而是在该给定时间之后的一个小时。此外,我给定的时间只能在同一天,并且不晚于23:30,这意味着我只关心给定的时间是否不晚于23:00。

我如何将所有这些放在一起?

要调整一小时,只需在比较中添加一小时(以毫秒 (60 * 60 * 1000) 为单位)。 要忽略 2300 之后的任何给定时间,您需要在条件中添加另一个子句。 所以这样的事情可能会做到:

if (new Date(givenMs).getHours() < 23
    && curTime > givenMs + 3600000) {
    // time has passed
}

希望这有所帮助。

尝试使用 .toJSONString.prototype.replace()String.prototype.slice()

$("div").click(function() {
  var curDate = new Date(),
    curTime = curDate.toJSON(),
    givenTm = $(this).find(".em").attr("data-time")
    .replace(/('d+)(?=:)/, function(match) {
      return Number(match) + 1
    }),
    curr = curTime.slice(11, -8).replace(":", ""),
    given = givenTm.replace(":", "");   
  if (curr < 2330 && given < 2330) {
    // time has passed
    console.log("currTime:", curr, "givenTime:", given,
      "time has not passed")
  } else {
    console.log("time has passed")
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div>click
  <div class="em" data-time="17:30">
  </div>