Comparing dates with javascript

  • 19 January 2015
  • 2 replies
  • 2 views

Badge +2

I'm having problems comparing two dates in some javascript i have written (i'm new at this).  The code takes a date from the datepicker on a form (EffectiveDate) and the start of the financial year and compares the two.  However even though the dates are  pulling through correctly (i checked the variables through alerts), any date entered seems trigger an alter to say its less than the start of the financial year. I've tried converting the dates to numbers and all sorts of other things and i'm stumped.

Any ideas?

function CheckDate(){

var curDate = new Date();

var curMonth = curDate.getMonth();

var curYear= curDate.getFullYear();

var inputdate = NWF$('#' + varEffectiveDate).datepicker();

if(curMonth>3){

var taxYear= curYear

} else {

var taxYear =curYear-1;

}

var startYear = new Date();

startYear.setDate(1);

startYear.setMonth(3);

startYear.setFullYear(taxYear);

if(inputdate<startYear);

alert("you cannot input a date before the start of the financial year");

}


2 replies

Badge +9

First of all use allways jslint/jshint to detect errors and potential problems in your JS coding!

var inputdate = NWF$('#' + varEffectiveDate).datepicker();

This let inputdate be a jquery object not a date string!

To get the date value you have to use the following coding:

var inputdate = NWF$('#' + varEffectiveDate).val();

The format of the date depends on your local settings.

Kind regards

Manfred

Badge +2

It would have helped if i wrote my final if statement correctly.  It now works :

function CheckDate(){

var curDate = new Date();

var curMonth =

curDate.getMonth();

var curYear= curDate.getFullYear();

var inputdate = NWF$('#' + varEffectiveDate).val();

var iDay = inputdate.slice(0,2)

var iMonth = inputdate.slice(3,5)

var iYear = inputdate.slice(6,10)

var inputDateFormatted = new Date();

inputDateFormatted.setDate(iDay);

inputDateFormatted.setMonth(iMonth);

inputDateFormatted.setFullYear(iYear);

if(curMonth>3){

var taxYear= curYear

} else {

var taxYear =curYear-1;

}

var startYear = new Date();

startYear.setDate(1);

startYear.setMonth(4);

startYear.setFullYear(taxYear);

if(inputDateFormatted < startYear) {

alert("you cannot input a date before the start of the financial year");

NWF$('#' + varEffectiveDate).datepicker("setDate",null);

}

}


Reply