繁体   English   中英

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

[英]jQuery - check if current date and time is within 24 hours of selected date and time

我目前有以下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小时之内,但不知道如何实现此目标,因此,我们将不胜感激! :)

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

$('#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
    }
});

我认为这也将为您工作-

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

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

暂无
暂无

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

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