-1

Trying to add a number new date in javascript

How ever the number is coming in from a json file.

Here is what i have.

myObj = {"yearsleft":"2", "name": "john"};

var term = myObj.yearsleft;
var d = new Date();

var year = d.getFullYear() + term.toString();
var month = d.getMonth()+1;
var day = d.getDate();
var output = ''+ (day<10 ? '0' : '') + day + '/' + (month<10 ? '0' : '') + month + '/' + year;
alert(output);

above is a working example

However its just appending 2 to the end of the year. which isnt what i want it to do. I want it to add onto 2019 if that's possible.

m4c
  • 11
  • 5
  • 1
    term is string convert to number and add var year = d.getFullYear() + parseInt(term.toString()); – P D K Pavan Kumar Jun 21 '19 at 09:00
  • You mean in the original json file? Because its impossible for me to change that. as its not something i can change. – m4c Jun 21 '19 at 09:02
  • Not on the json file. Just the convert `term` variable to number :) – Eddie Jun 21 '19 at 09:02
  • 1
    @Eddie thank you your link helped me lots. – m4c Jun 21 '19 at 09:05
  • You can't add values to date parts without testing if the result is a valid date. E.g. 29 Feb 2004 + 2 years is 29 Feb 2006, but that's an invalid date because 2006 wasn't a leap year. – RobG Jun 21 '19 at 13:52

3 Answers3

0

You are adding string to a number, convert it to int and then add.

var year = d.getFullYear() + parseInt(term.toString(), 10);
Jaydeep
  • 1,686
  • 1
  • 16
  • 29
  • Be careful, [`parseInt`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt) does NOT default to base 10... so always use `parseInt(..., 10)` – freefaller Jun 21 '19 at 09:03
  • @freefaller—[yes it does](http://ecma-international.org/ecma-262/9.0/#sec-parseint-string-radix), unless the string starts with `'0x'`, when it defaults to base 16. P.S. MDN is just a public wiki that anyone can contribute to, it is not normative. ECMA-262 is. – RobG Jun 21 '19 at 13:38
  • @RobG - fair enough, it must have changed over the years, because it used to default to base-8 if you weren't careful – freefaller Jun 21 '19 at 15:17
0

Convert to a number - currently you're concatenating not adding.

myObj = {"yearsleft":"2", "name": "john"};

var term = myObj.yearsleft;
var d = new Date();

var year = d.getFullYear() + +term;
var month = d.getMonth()+1;
var day = d.getDate();
var output = ''+ (day<10 ? '0' : '') + day + '/' + (month<10 ? '0' : '') + month + '/' + year;
console.log(output);
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
0
d.getFullYear() + parseFloat(term);

Seem to have fixed it for me.

m4c
  • 11
  • 5
  • it makes more sense to use parseInt instead of Float, so use `parseInt(term, 10)` the 10 is for the base, like @freefaller said on a different answer, parseInt doesn't always default to base 10, so you should add it just in case. – Reda Drissi Jun 21 '19 at 09:06