javascript date validation not validation February 31 - javascript

I am trying to write some code with will validate form data. I have a date field which should have a mm/dd/yyyy format. I needed to catch exceptions such as February 31, so I added this code:
var d = new Date(dob);
if (isNaN(d.getTime())) { //this if is to take care of February 31, BUT IT DOESN'T!
error = 1;
message += "<li>Invalid Date</li>";
} else {
var date_regex = /^(0[1-9]|1[0-2])\/(0[1-9]|1\d|2\d|3[01])\/(19|20)\d{2}$/;
var validFormat = date_regex.test(dob);
if (!(validFormat)) {
error = 1;
message += "<li>Invalid date format - date must have format mm/dd/yyyy</li>";
}
}
However I found something very weird: while the date 02/32/2000 errors as an invalid date, 02/31/2000 does not!

Due to what I said in the comments...
Another way you could check if a date is valid is by checking whether or not the stuff you passed into the new Date function is the same as what comes out of it, like this:
// Remember that the month is 0-based so February is actually 1...
function isValidDate(year, month, day) {
var d = new Date(year, month, day);
if (d.getFullYear() == year && d.getMonth() == month && d.getDate() == day) {
return true;
}
return false;
}
then you could do this:
if (isValidDate(2013,1,31))
and it would return true if valid and false if invalid.

After wrecking my head with the obscurity of Date .getMonth() (and also weekday by .getDay()) being 0-index (despite year, day and all the others not being like so... oh god...) I've re-wrote Jeff's answer to make it more readable and more friendly-usable to whom consume the method from outside.
ES6 code
You can call passing month as 1-indexed as you'd normally expect.
I've parsed inputs using Number constructor so I can use strict equality to more confidently compare values.
I'm using the UTC version methods to avoid having to deal with the local timezone.
Also, I broke steps down into some variables for the sake of readability.
/**
*
* #param { number | string } day
* #param { number | string } month
* #param { number| string } year
* #returns { boolean }
*/
function validateDateString(day, month, year) {
day = Number(day);
month = Number(month) - 1; //bloody 0-indexed month
year = Number(year);
let d = new Date(year, month, day);
let yearMatches = d.getUTCFullYear() === year;
let monthMatches = d.getUTCMonth() === month;
let dayMatches = d.getUTCDate() === day;
return yearMatches && monthMatches && dayMatches;
}

Are you able to use a library?
My first port of call for date handling in Javascript is moment.js: "A javascript date library for parsing, validating, manipulating, and formatting dates."

The ususal way to validate a 'mm/dd/yyyy' date string is to create a date object and verify that its month and date are the same as the input.
function isvalid_mdy(s){
var day, A= s.match(/[1-9][\d]*/g);
try{
A[0]-= 1;
day= new Date(+A[2], A[0], +A[1]);
if(day.getMonth()== A[0] && day.getDate()== A[1]) return day;
throw new Error('Bad Date ');
}
catch(er){
return er.message;
}
}
isvalid_mdy('02/31/2000')
/* returned value: (Error)Bad Date */

Assuming month input is 1-12 (1-based, not 0-based):
function isValidDate(year, month, day) {
var d = new Date(year, month - 1, day);
return month == d.getMonth() + 1;
}
isValidDate(2019, 12, 0); //=> false
isValidDate(2020, 2, 29); //=> true
isValidDate(2021, 2, 29); //=> false
isValidDate(2022, 2, 31); //=> false

Basically an alternative to the above-mentioned examples
function (date) {
if (!/(0[1-9]|1[0-9]|2[0-9]|3[0-1])\/(0[1-9]|1[0-2])\/([1-2][0-9]{3})/g.test(date))
{
alert('Incorrect date format please follow this form: dd/mm/yyyy');
return;
}
else
{
// secondary validation
const parts = (date).split('/').map((p) => parseInt(p, 10));
let day = Number(parts[0]);
let month = Number(parts[1]) - 1; // 0-indexed month
let year = Number(parts[2]);
let d = new Date(year, month, day);
if (!(d.getFullYear() == year && d.getMonth() == month && d.getDate() == day))
{
alert('Incorrect date, please enter the correct day entry');
return;
}
}
}

I may be a little late for posting an answer but here is what worked best for me
var user_date = (`${user_values.month_value} ${user_values.date_value} , ${user_values.year_value}`)
const d = new Date(user_date);
let day = d.getDate()
if(user_values.date_value != day){
setdate_validation({
display:'flex'
})
}
else{
setdate_validation({
display:'none'
})
console.log(user_values)
so in the above code what happens is i get different inputs from my user like one dropdown for date another for month and so on , i collect them and store it with .getdate() now .getdate() function returns the value of day , so if i stored (02 21 , 2002) then the .getdate() will return 21 ,
but there is a catch if i enter an invalid date like (02 30, 2002) where 30 is invalid in month of february then the .getdate() function returns not the same date but the date in next month or increment as much you are far away from a valid date like if 28 is valid and I entered 29 then .getdate() will show 1 as the output so i just compare the result of .getdate() with my current date value which is entered and if it is not same then the date is invalid.
(this code is from react using usestates)

Related

Date validation and relative delta between two dates in javascript

I have an interface where I receive a date in this format: Month/Year, ex: 11/2022.
I would like to verify that this is a valid date.
I use the datatables editor. The configuration (see below) of the field works well, but since the user can enter the date himself without going through the calendar, there is a risk that the date entered is incorrect. It doesn't work like an input mask. So i need to validate the date in the code.
{
type: "datetime",
label: "Date:",
name: "Date",
def: function () { return new Date(); },
format: 'MM/YYYY',
fieldInfo: 'Format: Month/Year (ex: 12/2022)',
keyInput: true
}
The date should not be accepted if the difference between this date and today's date is less than 3 months.
It means that, compared to today, all dates before July will have to be rejected.
Currently I can do this with the relativedelta method of the python dateutil module. But as the validation must be done on the client side, I would like to do this in javascript (which I know very little).
The example below shows how to do this. You should take advantage of the HTML 5 input types to validate your dates. You also need to calculate 3 months from now in myEpoch and then compare it to the date/time given
HTML:
<p>
Date & Time: <input id="foo" type="datetime-local" />
</p>
JavaScript:
var myEpoch = new Date();
myEpoch.setMonth(myEpoch.getMonth() + 3);
myEpoch = myEpoch.getTime();
var foo = document.getElementById("foo");
if (foo.value < myEpoch) {
//show a message saying this date is invalid
}
Since user is entering date in MM/yyyy format, so i'm assuming that you take 1 as a date into account, i.e., if input is 03/2020, you would consider it as: 01/03/2020. Right? If
so, then you can do the following to validate this date:-
function isValidDate(inputDate) {
// Unfortunately JS doesn't have any in-built function to validate date in MM/yyyy format. Hence regex comes to the rescue
var regex = /^([0-9]{1,2})\/([0-9]{4,4})$/;
var matches = regex.exec(inputDate);
if (!matches || matches.length != 3) {
throw new Error('Please provide date in MM/yyyy format');
}
var inputMonth = matches[1]; // Return month from input date
var inputYear = matches[2]; // Return year from input date
var finalDate = inputMonth+ '/01/' + inputYear;
// Check if entered date is valid or not
var parsedDate = Date.parse(finalDate);
if (isNaN(parsedDate)) {
throw new Error('Unable to parse date.');
}
// Check if it is less than 3 months or not.
var isValid = !isLessThan3Months(new Date(finalDate), new Date());
return isValid;
}
function isLessThan3Months(dateToCompare, currentDate) {
var diffYears = currentDate.getFullYear() - dateToCompare.getFullYear();
var diffMonths = currentDate.getMonth() - dateToCompare.getMonth();
var diffDays = currentDate.getDate() - dateToCompare.getDate();
var months = diffYears * 12 + diffMonths;
if (diffDays > 0) {
months += '.' + diffDays;
} else if (diffDays < 0) {
months--;
months +=
'.' +
(new Date(currentDate.getFullYear(), currentDate.getMonth(), 0).getDate() + diffDays);
}
return months < 3;
}
isValidDate('03/2020');
So now, by calling isValidDate with user's input date in MM/yyyy format, you should be able to check if it is valid or not.
For this, you won't need to use any third party javascript library. Just plain javascript is enough.
You should probably use Moment.js, because working with the raw Date object is fiddly.
If you would rather use plain JavaScript, then the following might be of use:
const moreThan3MonthsHence = ({ utcYear, utcMonth },
now = new Date,
target = new Date(Date.UTC(utcYear, utcMonth)),
threeMonthsHence = addMonths(new Date(now.valueOf()), 3)) =>
(target > threeMonthsHence)
const validate = (str,
[utcMonth, utcYear] = str.split('/'),
date = new Date(Date.UTC(+utcYear, (+utcMonth)-1))) =>
moreThan3MonthsHence({ utcYear: date.getUTCFullYear(), utcMonth: date.getUTCMonth() })
const addMonths = (date, months, d = date.getDate()) => {
date.setMonth(date.getMonth() + +months);
// If rolled over to next month, set to last day of previous month
if (date.getDate() != d) {
date.setDate(0);
}
return date;
}
// Note: input is one-based months
console.log(validate('07/2020')) // true
console.log(validate('06/2020')) // false
console.log(validate('12/2019')) // false
Notes
now is internally represented as the milliseconds since the Unix epoch. Note this includes the current time of day.
target is the milliseconds since the Unix epoch of midnight on the supplied UTC date.
threeMonthsHence is the milliseconds since the Unix epoch of now (including time of day), plus three months.
validate parses the input string.
addMonths is necessary because the built-in function can roll-over into a new month with unexpected behavior.
Finally to solve my problem I mixed the solutions proposed by #Sumit Parakh and #ControlAltDel.
function isValidDate(inputDate) {
var regex = /^([0-9]{1,2})\/([0-9]{4,4})$/;
var matches = regex.exec(inputDate);
var parsedDate = 0;
if (!matches || matches.length != 3) {
throw new Error('Please provide date in MM/yyyy format');
}
else {
var inputMonth = matches[1]; // Return month from input date
var inputYear = matches[2]; // Return year from input date
var finalDate = inputMonth+ '/01/' + inputYear;
// Check if entered date is valid or not
var parsedDate = Date.parse(finalDate);
if (isNaN(parsedDate)) {
parsedDate = 0;
//throw new Error('Unable to parse date.');
}
return parsedDate;
}
var myEpoch = new Date();
myEpoch.setMonth(myEpoch.getMonth() + 3);
myEpoch = myEpoch.getTime();
finalDate = isValidDate(date_peremption.val());
if (finalDate == 0){
date_received.error("This date is invalid");
}
else if(finalDate < myEpoch) {
date_received.error("The date must be more than three months last");
}
It's not very elegant, but it works. Thanks everyone

Date picker not working in Internet Explorer due to inability to convert strings to numbers

I am making a date-filter that takes an input string using https://www.npmjs.com/package/js-datepicker formatted as such "MM/DD/YYYY" then attempting to convert that to a number to use it in a conditional which will conditionally show items that fall w/in the specified date. My function takes undefined/NaNs and fills in Date.parse("01/01/1970") or Date.parse("01/01/3000") depending on start or end date. My problem is that in IE all of my dates are returning NaN so the filter wont work - it works fine in Chrome and Edge, but does nothing in IE (since everything falls between 1971 and 3000.
I've tried slicing and dicing the data up a bunch of different ways, but it seems I can't even convert "10" to 10 in ie w/o getting NaN.
var isd: any = startDate[0].value;
console.log(isd);
console.log(typeof isd);
var parts = isd.split("/");
console.log(parts[0], parts[1], parts[2]);
let year = parts[2];
let month = parts[0]; // 0 is january
let day = parts[1];
console.log(year, month, day);
console.log(typeof year, typeof month, typeof day)
year = parseInt(year);
month = parseInt(month) - 1;
day = parseInt(day);
console.log(year, month, day);
let year2 = parts[2];
let month2 = parts[0]; // 0 is january
let day2 = parts[1];
year2 = parseFloat(year2);
month2 = parseFloat(month2) - 1;
day2 = parseFloat(day2);
console.log(year2, month2, day2);
let year3 = parts[2];
let month3 = parts[0]; // 0 is january
let day3 = parts[1];
year3 = Number(year3);
month3 = Number(month3) - 1;
day3 = Number(day3);
console.log(year3, month3, day3);
var inputStartDate: any = new Date(year, month, day);
inputStartDate = inputStartDate.toString();
// console.log(this.startDate, this.endDate, thisStartDate, thisEndDate);
console.log(isd, ied, inputStartDate, inputEndDate);
I expect that when I do Number||parseInt||parseFloat("10") to get 10 back. but instead I get only NaN.
my console.log looks like:
10/10/2019
string
10 10 2019
2019 10 10
string string string
NaN NaN NaN (x3 lines)
‎10‎/‎16‎/‎2019 Invalid Date NaN
Thanks in advance
Alright, so here's how I worked around this issue:
in the documentation, js-datepicker has an onSelect method which has access to that instance of datepicker (https://www.npmjs.com/package/js-datepicker#onselect) - the datepicker instance has a dateSelected attribute which is either undefined (no date selected) or a Date object matching the user selection. I just set this dateSelected equal to a more globally scoped var (inputStartDate and inputEndDate) and used inputStart/EndDate.getTime() in my conditionals. I also handled the null dates by setting them as either much earlier or later than the period the objects I was filtering against would be in. Here's an example of my onSelect Code:
onSelect: (instance: any) => {
if (instance.el.id === "filter-start-date") {
if (instance.dateSelected === undefined) {
inputStartDate = new Date("05-02-91");
// console.log("happy birthday!");
} else {
inputStartDate = instance.dateSelected; // date obj
}
} else if (instance.el.id === "filter-end-date") {
if (instance.dateSelected === undefined) {
inputEndDate = new Date("01-01-3031");
// console.log("welcome to the future");
} else {
inputEndDate = instance.dateSelected;
}
}
This solution circumvented the whole process of grabbing data from the input field set by the datepicker which was somehow incompatible with selector methods/dom tree gettting/setting/data manipulation.

JavaScript validate date and return last available date of calendar

I want to validate my date if date not exits in calendar then return me last available date of calendar,
Example 01
Input Date : 31-Feb-2017
Return Result : 28-Feb-2017
Example 02
Input Date : 31-March-2017
Return Result : 31-March-2017
Example 03
Input Date : 31-Apr-2017
Return Result : 30-Apr-2017
Example 04
Input Date : 31-Jun-2017
Return Result : 30-Jun-2017
Example 05 with Leaf Year
Input Date : 31-Feb-2020
Return Result : 29-Feb-2020
This is i am first trying to validate date using below function,how i can make logic for above dates.
function isValidDate(year, month, day) {
var d = new Date(year, month, day);
if (d.getFullYear() == year && d.getMonth() == month && d.getDate() == day) {
return true;
}
return false;
}
The last day of the month is given by the zero day of the following month, so:
function getDate(year, month, day) {
var d = new Date(year, month, day);
if (d.getMonth() == month) {
return d;
}
return new Date(year, +month + 1, 0);
}
console.log(getDate(2017,1,29).toString());
console.log(getDate(2017,0,32).toString());
BTW, to test for a valid date you only need to test the month since if the month is larger than months in a year, it will affect both month and year. If the day is greater than the number of days in the month it will affect the month too. Nothing affects the year (unless you pass a year less than 100, in which case it's treated as 1900 + year).
You can try something like this:
Explanation as per spec:
When we call date constructor with 2 or more arguments, it tries to process using following constructor ref:
new Date (year, month [, date [, hours [, minutes [, seconds [, ms ] ] ] ] ] )
Here if any value that is not passed, it will be set as NaN and later will be parsed to +0. Hence timestamp is 0:0:0
Now the trick is in a function called internally: MakeDay.
As you see point 8, it returns
Day(t) + dt − 1
Here Day(t) would return number of milliseconds and date would be calculated based on dt - 1. Since we are passing 0, date value would be -1 + milliseconds and hence it returns previous day.
Another alternate would be to create date for 1st of next month and subtract 1 as day or sec. You can select anyone based on the need,
function isValidDate(year, month, day) {
var d = new Date(year, month, day);
return !!(d.getFullYear() == year && d.getMonth() == month && d.getDate() == day)
}
function computeLastPossibleDate(y,m,d){
return new Date(y, m+1, 0);
}
function test(y,m,d){
return isValidDate(y,m,d) ? new Date(y,m,d) : computeLastPossibleDate(y,m,d)
}
// 31st Feb.
console.log(test(2017, 1, 31).toString())
// 31st March
console.log(test(2017, 2, 31).toString())
// 31st April
console.log(test(2017, 3, 31).toString())
// 50th Dec.
console.log(test(2017, 11, 50).toString())
Note: If there is anything missing, please share it as a comment with your vote. Just vote without comment will not help anyone.
function isValidDate(year, month, day) {
var d = new Date(year, month, day);
if (d.getFullYear() == year && d.getMonth() == month && d.getDate() == day) {
return d;
}
else
rturn new Date(year, month, 0);;
}
function isValidDate(year, month, day) {
if(month<=12){
var temp_day=day;
var d = new Date(year, month, day);
var lastDay = new Date(d.getFullYear(), d.getMonth(),0);
var getlastday=lastDay.getDate();
if(getlastday<=day){
//var date=(d.getDate())+"/"+(d.getMonth())+"/"+(d.getFullYear());
var date=(getlastday)+"-"+(month)+"-"+(lastDay.getFullYear());
return date;
}else{
//var date=(lastDay.getDate())+"-"+(lastDay.getMonth())+"-"+(lastDay.getFullYear());
var date=(day)+"/"+(month)+"/"+(year);
return date;
}
}
else{
return "month not valid";
}
}
try this code

How to check if date is in this week in javascript?

I have this date "2016-04-23T11:45:00Z" and I want to check this date in this week or not ?
Thanks,
Dates are hard, I would always suggest using a library dedicated to date handling as it reduces the chances of errors in your code.
MomentJS is a good one.
var now = moment();
var input = moment("2016-04-17T11:45:00Z");
var isThisWeek = (now.isoWeek() == input.isoWeek())
Edit: Please note as of 2020 moment may not be a good choice for new projects
This seems to be working for me.
function isDateInThisWeek(date) {
const todayObj = new Date();
const todayDate = todayObj.getDate();
const todayDay = todayObj.getDay();
// get first date of week
const firstDayOfWeek = new Date(todayObj.setDate(todayDate - todayDay));
// get last date of week
const lastDayOfWeek = new Date(firstDayOfWeek);
lastDayOfWeek.setDate(lastDayOfWeek.getDate() + 6);
// if date is equal or within the first and last dates of the week
return date >= firstDayOfWeek && date <= lastDayOfWeek;
}
const date = new Date();
const isInWeek = isDateInThisWeek(date);
<div ng-app="myApp">
<div class="container" ng-controller="Ctrl_List">
<h1>{{currentDate}}</h1>
<h1>{{numberCurrentDateWeeks}}</h1>
<h1>{{yourDate}}</h1>
<h1>{{numberYourDateWeeks}}</h1>
</div>
</div>
......
angular.module('myApp', [])
.controller("Ctrl_List", ["$scope", "$filter", function(s, $filter) {
s.yourDate = '2016-04-23T11:45:00Z'
s.currentDate = new Date();
s.numberCurrentDateWeeks = $filter('date')(s.currentDate, "w");
s.numberYourDateWeeks = $filter('date')(s.yourDate, "w");
}]);
then you got the Week numbers just compare or do whatever you like
cheers !
You can do that without any libraries by checking if the date.getTime() (milliseconds since epoch) is between last monday and next monday:
const WEEK_LENGTH = 604800000;
function onCurrentWeek(date) {
var lastMonday = new Date(); // Creating new date object for today
lastMonday.setDate(lastMonday.getDate() - (lastMonday.getDay()-1)); // Setting date to last monday
lastMonday.setHours(0,0,0,0); // Setting Hour to 00:00:00:00
const res = lastMonday.getTime() <= date.getTime() &&
date.getTime() < ( lastMonday.getTime() + WEEK_LENGTH);
return res; // true / false
}
(one week in ms = 24 * 60 * 60 * 1000 * 7 = 604,800,000)
May not be the most optimal solution, but I think it's quite readable:
function isThisWeek (date) {
const now = new Date();
const weekDay = (now.getDay() + 6) % 7; // Make sure Sunday is 6, not 0
const monthDay = now.getDate();
const mondayThisWeek = monthDay - weekDay;
const startOfThisWeek = new Date(+now);
startOfThisWeek.setDate(mondayThisWeek);
startOfThisWeek.setHours(0, 0, 0, 0);
const startOfNextWeek = new Date(+startOfThisWeek);
startOfNextWeek.setDate(mondayThisWeek + 7);
return date >= startOfThisWeek && date < startOfNextWeek;
}
This link explaines, how to do this without using any js libraries. https://gist.github.com/dblock/1081513
Code against link death:
function( d ) {
// Create a copy of this date object
var target = new Date(d.valueOf());
// ISO week date weeks start on monday
// so correct the day number
var dayNr = (d.getDay() + 6) % 7;
// Set the target to the thursday of this week so the
// target date is in the right year
target.setDate(target.getDate() - dayNr + 3);
// ISO 8601 states that week 1 is the week
// with january 4th in it
var jan4 = new Date(target.getFullYear(), 0, 4);
// Number of days between target date and january 4th
var dayDiff = (target - jan4) / 86400000;
// Calculate week number: Week 1 (january 4th) plus the
// number of weeks between target date and january 4th
var weekNr = 1 + Math.ceil(dayDiff / 7);
return weekNr;
}
I managed to do it with this simple trick and without any external library.
Considering monday as the first day of the week, the function takes as parameter a date string and do the validation before checking if the day indeed is in the current week.
function isInThisWeek(livr){
const WEEK = new Date()
// convert delivery date to Date instance
const DATEREF = new Date(livr)
// Check if date instance is in valid format (depends on the function arg)
if(DATEREF instanceof Date && isNaN(DATEREF)){
console.log("invalid date format")
return false}
// Deconstruct to get separated date infos
const [dayR, monthR, yearR] = [DATEREF.getDate(), DATEREF.getMonth(), DATEREF.getFullYear()]
// get Monday date
const monday = (WEEK.getDate() - WEEK.getDay()) + 1
// get Saturday date
const sunday = monday + 6
// Start verification
if (yearR !== WEEK.getFullYear()) { console.log("WRONG YEAR"); return false }
if (monthR !== WEEK.getMonth()) { console.log("WRONG MONTH"); return false }
if(dayR >= monday && dayR <= sunday) { return true }
else {console.log("WRONG DAY"); return false}
}
In the comments I saw that you stated that your week starts on Monday.
In that case, I guess it'd be a good idea to calculate the ISO week number of the 2 dates and see if you get the same week number for both of them.
To calculate the ISO week number, check this answer:
In case anyone else's week starts on Sunday instead, you can use this answer to calculate the week number accordingly.
then you can do something like this:
function isSameWeek(date1, date2) {
return date1.getWeekNumber() === date2.getWeekNumber();
}
const isDateInThisWeek = (date) => {
const today = new Date();
//Get the first day of the current week (Sunday)
const firstDayOfWeek = new Date(
today.setDate(today.getDate() - today.getDay())
);
//Get the last day of the current week (Saturday)
const lastDayOfWeek = new Date(
today.setDate(today.getDate() - today.getDay() + 6)
);
//check if my value is between a minimum date and a maximum date
if (date >= firstDayOfWeek && date <= lastDayOfWeek) {
return true;
} else {
return false;
}
};

how to alert if the input date is greater than defined date in js

I am having an input date field in my form. In my date field
i need to alert an error if the input date is greater than any date i define before
here is what i code :
$(document).ready(function () {
var date = new Date(2016,2,1); //the defined date is 1 March 2016
var day = date.getDate();
var month = date.getMonth();
month = month + 1;
if(day < 10){
day = '0' + day;
}
if(month < 10){
month='0'+month;
}
someday = day + '/' + month + '/' + date.getFullYear();
$("#q1 input").blur(function(){ //#q1 is the ID for the input field.
if($('#q1 input').val() > someday){
alert('the input is bigger than the defined');
}else{
alert('the defined is bigger than the input ');
}
});
});
To compare Dates is very straight forward. Most operators coerce the operands to number, and Dates return their time value so to see if today is before or after say 1 March 2016, create two Dates and compare them:
var epoch = new Date(2016,2,1); // Create date for 2016-03-01T00:00:00
var now = new Date(); // Create a date for the current instant
now.setHours(0,0,0,0); // Set time to 00:00:00.000
if (now < epoch) {
alert('Before 1 March, 2016');
} else {
alert('On or after 1 March, 2016');
}
Or a bit more compact:
alert((now < epoch? 'Before':'On or after') + ' 1 March, 2016');
You might want to compare the values as in the date form, not the way you did.
Convert the input value into the form of date and compare it with the variable 'date'.
Compare the input date with the desired date that you defined. For example:
var d1 = new Date();
var d2 = new Date(d1);
var same = d1.getTime() === d2.getTime();
var notSame = d1.getTime() !== d2.getTime();
If you find it tricky, then there is an awesome js library called moment.js. It is very useful when playing with dates.
$(document).ready(function () {
var date=new Date(2016,2,1); //the defined date is 1 March 2016
var fixedDate = returnDate(date);// convert date in dd/mm/yyyy format
//#q1 input will search a child input inside an #q1 dom element, which probably not the case
// input#q1 will refer to input with id #q1
// You can directly query the input since it has id #q1 so #q1 input is not correct
$("#q1").blur(function(){ //#q1 is the ID for the input field.
var d2 = new Date($('#q1').val());
var inputDate = returnDate(d2); // convert input date in dd/mm/yyyy format
if(inputDate > fixedDate){ // compare two dates
console.log('the input is bigger than the defined');
}else{
console.log('the defined is bigger than the input ');
}
});
});
// Write a general function to convert date in dd/mm/yyyy format
function returnDate(date){
var day=date.getDate();
var month=date.getMonth();
month=month+1;
if(day<10){
day='0'+day;
}
if(month<10){
month='0'+month;
}
var someday=day+ '/' + month + '/' + date.getFullYear();
return someday;
}
JSFIDDLE
EDIT 1
Use ternary operator instead of if-else
inputDate > fixedDate? (console.log("the input is bigger than the defined")):(console.log("the defined is bigger than the input"))
with ternary operator

Categories

Resources