jQuery - 检查当前日期和时间是否在所选日期和时间的24小时内

时间:2016-03-01 19:43:58

标签: javascript jquery date

我目前有以下jQuery: -

$('#datepicker').on('change', function(e) {

  var selected_date = $('#datepicker').datepicker('getDate');
  var today = new Date();

  today.setHours(0);
  today.setMinutes(0);
  today.setSeconds(0);

  var today_formatted = Date.parse(today);
  var selected_date_formatted = Date.parse(selected_date);

  var selected_time = $('#time').val();

  if (selected_date_formatted == today_formatted) {
    console.log('yes');
  } else {
    console.log('no');
  }
});

基本上检查当前日期是否与所选日期相同,这部分工作正常。

我需要做的是以某种方式检查当前日期和时间是否在所选日期和时间的24小时内,但不知道如何实现这一点,所以任何帮助将非常感谢! :)

2 个答案:

答案 0 :(得分:3)

基本上只需将日期对象转换为时间戳,并使用milliseconds检查它们是否在24小时内

$('#datepicker').on('change', function (e) {
    var selected_date = $('#datepicker').datepicker('getDate');
    var today = new Date();

      //Remove this to get current time, leave this to get time start of day
      today.setHours(0);
      today.setMinutes(0);
      today.setSeconds(0);

    var currentDateTimestamp = today.getTime();
    var selectedDateTimestamp = selected_date.getTime();

    //Check if the timestamp is within 24 hours, 24 hours = 60 seconds * 60 minutes * 24 hours * 1000 milliseconds
    if (Math.abs(currentDateTimestamp - selectedDateTimestamp) <= 60 * 60 * 24 * 1000) {
      //Within 24 hours
    }
});

答案 1 :(得分:2)

我认为这也适合你 -

var daydiff = (currentDate.getMilliseconds() - selectedDate.getMilliseconds()) / 86400000;

if (daydiff < 1) {
  //within 24h
} else {
  //not within 24h
}