In this short tip post, we will learn how to find out if a Date object represents a today DateTime.
Objective
To determine if a JavaScript Date object instance is a representation of a date/time that is “today”.
Approach
By using a JavaScript Date instance, we can use the
getDate(), getMonth() and getFullYear() methods, which return the day, month and year of a date, and compare them to today’s date, which we can fetch using new Date().
Code
Here is the code:
function isToday(dateParameter) {
var today = new Date();
return dateParameter.getDate() === today.getDate() && dateParameter.getMonth() === today.getMonth() && dateParameter.getFullYear() === today.getFullYear();
}
console.log("Is today ? ", isToday(new Date())); // true
console.log("Is today ? ", isToday(new Date('10-11-2014'))); // false
var today = new Date();
return dateParameter.getDate() === today.getDate() && dateParameter.getMonth() === today.getMonth() && dateParameter.getFullYear() === today.getFullYear();
}
console.log("Is today ? ", isToday(new Date())); // true
console.log("Is today ? ", isToday(new Date('10-11-2014'))); // false
Check out the codepen for a live demo of the code.
See the Pen
Is date today? by Shahid Shaikh (@codeforgeek)
on CodePen.
Love JavaScript? Learn more about it here.