[英]jQuery - check if current date and time is within 24 hours of selected date and time
I currently have the following jQuery:- 我目前有以下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! 我需要做的是以某种方式检查当前日期和时间是否在所选日期和时间的24小时之内,但不知道如何实现此目标,因此,我们将不胜感激! :) :)
Basically just convert your date objects to timestamps, and check if they are within 24 hours using milliseconds
基本上只是将日期对象转换为时间戳,并检查它们是否在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
}
});
I think this will also work for you - 我认为这也将为您工作-
var daydiff = (currentDate.getMilliseconds() - selectedDate.getMilliseconds()) / 86400000;
if (daydiff < 1) {
//within 24h
} else {
//not within 24h
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.