检查字符串中的时间是否大于当前时间

时间:2018-08-24 00:02:38

标签: javascript jquery datetime momentjs

我有一些类似的字符串

例如'8:00 AM''12:00 PM''2:00 PM'

如何检查JavaScript或jquery以查看此时间是否已超过当前时间? 到目前为止,这是我尝试过的方法,但是isAfter方法似乎不起作用

var time = moment(startTime, 'HH:mm A'); //.format('HH:mm A');

if (time.isAfter(moment())) {
  yb.base.eventAlert("You can't create events in the past! Try refreshing your page", "info");
  return false;
}

更新-我想通了!

我不得不以“小时”为条件

if (moment().isAfter(time, 'hour minute')) {
  yb.base.eventAlert("You can't create events in the past! Try refreshing your page", "info");
  return false;
}

3 个答案:

答案 0 :(得分:0)

尝试使用此功能:

function checktime() {
  var dt = new Date(); //Get current time 
  var time = dt.getHours() + ":" + dt.getMinutes(); //Get hour and minutes
  var timeStr = document.getElementById('time').value; // Get string time 
  var parts = timeStr.split(':'); // Split string to get hours and minutes
  var hour = parseInt($.trim(parts[0]));

  // swap am & pm
  if (parts[1].match(/(AM|am)/)) {
    if (hour == 12) {
      // easily flip it by adding 12
      hour = 0;
    }
    parts[1] = parseInt(parts[1])
  } else {
    if (hour < 0) {
      hour = hour + 12
    }
    parts[1] = parseInt(parts[1]);
  }
  timeStr = hour + ':' + parts[1];

  if (hour > dt.getHours() && parts[1] > dt.getMinutes) {
    console.log("Past time");
    console.log(hour + "  " + dt.getHours());
  } else if (hour == dt.getHours() && parts[1] > dt.getMinutes) {
    console.log("Past time");
    console.log(hour + "  " + dt.getHours());
  } else {
    console.log("Not Past time");
    console.log(hour + "  " + dt.getHours());
  }

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="time" placeholder="Insert time" />
<button onclick="checktime();">Check time</button>

答案 1 :(得分:0)

function isPastCurrentTime (time){ 
  let timeNow = new Date(); 

  //converts timeNow to  just the date string
  let date = timeNow.toLocaleDateString();

  //adds the time to check to the date string, converts it to milliseconds
  //then truncates the last four digits to compare minutes
  //instead of milliseconds
  let timeToCheck = Math.floor(new Date(date + ' ' + time).getTime() / 60000); 


  //converts timeNow to milliseconds, then truncates the last four digits
  //to compare minutes instead of milliseconds
  let currentTime = Math.floor(timeNow.getTime() / 60000);

  return timeToCheck > currentTime;  
}

答案 2 :(得分:0)

这解决了

if (moment().isAfter(time, 'hour minute')) {
  yb.base.eventAlert("You can't create events in the past! Try refreshing your page", "info");
  return false;
}