简体   繁体   中英

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

I currently have the following 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');
  }
});

Which basically checks to see if the current date is the same as the selected date and this part is working fine.

What I need to do is somehow check if the current date and time is within 24 hours of the selected date and time but have no idea how I can achieve this so any help would be much appreciated! :)

Basically just convert your date objects to timestamps, and check if they are within 24 hours using 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
    }
});

I think this will also work for you -

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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