I get three variables through a user input, that contain the year of a date, the month and the day. I've already checked if the month var is between 1–12 and so on.
Now I want to check if it's a real date and not a date that doesn't exist like 31–06–2011.
My first idea was to make a new Date instance:
var year = 2011;
var month = 5; // five because the months start with 0 in JavaScript - June
var day = 31;
var myDate = new Date(2011,5,31);
console.log(myDate);
But myDate doesn't return false, because it's not a valid date. Instead it returns 'Fri Jul 01 2011 [...]'.
Any ideas how I can check for an invalid date?
By default, JavaScript will use the browser's time zone and display a date as a full text string: You will learn much more about how to display dates, later in this tutorial. Date objects are created with the new Date () constructor. new Date () creates a new date object with the current date and time: Date objects are static.
Store the date object into a variable d. Check if the variable d is created by Date object or not by using Object.prototype.toString.call (d) method. If the date is valid then the getTime () method will always be equal to itself.
When a Date object is created, a number of methods allow you to operate on it. Date methods allow you to get and set the year, month, day, hour, minute, second, and millisecond of date objects, using either local time or UTC (universal, or GMT) time.
The getTime () method returns the number of milliseconds since January 1, 1970: The getFullYear () method returns the year of a date as a four digit number: The getMonth () method returns the month of a date as a number (0-11): In JavaScript, the first month (January) is month number 0, so December returns month number 11.
Try this:
if ((myDate.getMonth()+1!=month)||(myDate.getDate()!=day)||(myDate.getFullYear()!=year))
alert("Date Invalid.");
if ((myDate.getDate() != day) ||
(myDate.getMonth() != month - 1) ||
(myDate.getFullYear() != year))
{
return false;
}
JavaScript just converts entered in Date
constructor month
, year
, day
, etc.. in simple int value (milliseconds) and then formats it to represent in string format. You can create new Date(2011, 100, 100)
and everythig will ok :)
You could possibly do what you do now and construct a new Date object and then afterwards check the value of myDate.getFullYear(), myDate.getMonth(), myDate.getDate(), to ensure that those values match the input values. Keep in mind that getMonth() and getDate() are 0 indexed, so January is month 0 and December is month 11.
Here's an example:
function isValidDate(year, month, day) {
var d = new Date(year, month, day);
return d.getFullYear() === year && d.getMonth() === month && d.getDate() === day;
}
console.log(isValidDate(2011,5,31));
console.log(isValidDate(2011,5,30));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With