Reputation: 5622
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! :)
Upvotes: 2
Views: 2875
Reputation: 824
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
}
});
Upvotes: 3
Reputation: 76
I think this will also work for you -
var daydiff = (currentDate.getMilliseconds() - selectedDate.getMilliseconds()) / 86400000;
if (daydiff < 1) {
//within 24h
} else {
//not within 24h
}
Upvotes: 3