1

I get wrong output for months that have 29,30,31th. Please help thanks.

    //EFFDATE = 29/03/2017;

    EFFDATE = document.mainform2.EFFDATE.value;
    var dayOfDate   = parseFloat(EFFDATE.substring(0,2));
    var monthOfDate = parseFloat(EFFDATE.substring(3,5));
    var yearOfDate  = parseFloat(EFFDATE.substring(6,10));

    var date1 = new Date;
    var date2 = new Date;
    date1.setDate(dayOfDate);
    date1.setMonth(monthOfDate -1);
    date1.setFullYear(yearOfDate);
    console.log(date1); 

For example i pick the 29th of March, the system output for date1 is friday march 01 2017.

i pick 30th of March it show friday march 02 2017

3 Answers 3

2

It is important to maintain a certain order when you are manipulating dates. Calling new Date will return a date object with the month February. But when you set the day to 29 using setDate, JavaScript will change the date to March, 01 as there is no February, 29 in 2017.

So you either have to set the month first, then the day. Or just use this code:

var EFFDATE = 29/03/2017;
new Date(EFFDATE.split('/').reverse().join('-'));
Sign up to request clarification or add additional context in comments.

Comments

0

The setMonth method has an optional second parameter for the day of the month. If it's absent, getDate() is used, and the date is still incomplete.

So this should solve the issue:

date1.setMonth(monthOfDate-1, dayOfDate);
date1.setFullYear(yearOfDate);

Comments

-1

Wrong but I'll leave it here for posterity

The second parameter to substring should be the number of characters you want not the index.

If you debugged this and looked at the value of EFFDATE.substring(3,5) you'd see 03/20 not 03 as you were probably thinking.

var dayOfDate   = parseFloat(EFFDATE.substring(0,2));
var monthOfDate = parseFloat(EFFDATE.substring(3,5));
var yearOfDate  = parseFloat(EFFDATE.substring(6,10));

should be:

var dayOfDate   = parseFloat(EFFDATE.substring(0,2));
var monthOfDate = parseFloat(EFFDATE.substring(3,2));
var yearOfDate  = parseFloat(EFFDATE.substring(6,4));

UPDATE

I was thinking of substr rather than `substring which is subtley different.

2 Comments

Fair enough I was thinking of substr which has the described behaviour. Oops

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.