检查时差是否小于45分钟,以及时间是否超过当前时间-AngularJS



用这样的代码在PHP中做这件事很容易;

if (strtotime($given_time) >= time()+300) echo "You are online";

但是在SO上找不到任何可以在javascript中做到这一点的东西。我想检查给定时间和当前时间之间的差异是否小于45分钟

例如

$scope.given_time = "14:10:00"
$scope.current_time = new Date();

我只关心时间部分。我需要从new Date();中提取时间部分,然后进行比较。

那么这应该是true

我如何使用Javascript实现这一点:

if ($scope.given_time - $scope.current_time < 45 minutes && if $scope.given_time > time()) {
   // do something
}

@Pete提供的以下功能解决了第一部分(45分钟部分)

function checkTime(time) {
  var date = new Date();
  var date1 = new Date((date.getMonth() + 1) + "/" + date.getDate() + "/" + date.getFullYear() + " " + time);
  var minutes = (date1.getTime() - date.getTime()) / (60 * 1000);
  if (minutes > 45 || (minutes < 0 && minutes > -1395)) { 
  // greater than 45 is todays time is above 45 minutes
  // less than 0 means the next available time will be tomorrow and the greater than -1395 means it will be more than 45 minutes from now into tomorrow
    document.write(time + ': true<br />');
  } else {
    document.write(time + ': false<br />');
  }
}

减去两个日期对象会产生以毫秒为单位的差异。因此,将其与45分钟内的毫秒数进行比较。

var date1 = new Date();
var date2 = new Date();
date2.setTime(date2.getTime() + (50 * 60 * 1000));  //adding 50 minutes just to see console message
    
if (date2-date1 >= 45*60*1000) {
    console.log("greater than 45 minutes");
}

将其与时间戳进行比较。IMO这是最简单的方法。我不知道这和angularJs有什么关系。

var currentTimeStamp = new Date().getTime(); //timestamp in ms
var beforeTimeStamp = startDate.getTime(); //timestamp in ms
if (currentTimeStamp - beforeTimeStamp < 45*60*1000 && currentTimeStamp - beforeTimeStamp > 0) {
  //do smth
}

请注意,startDate是例如通过登录创建的日期。

最新更新