0

i have the following code which creates a new object:

function Person(firstname, lastname, birth) {
this.name = firstname + " " + lastname;
this.bdate = {
 year: birth.getFullYear(),
 day: birth.getDate(),
 month: "January,Febuary,March,April,May,June,July,August,September,October,November,December".split(",")[birth.getMonth() - 1],
 monthnumber: birth.getMonth(),
 }
this.age = new Date().getFullYear() - birth.getFullYear();
}

var foo = new Person("Jon", "Doe", new Date(1996, 12, 5));
console.log(foo);

when i do the following code:

var foo = new Person("Jon", "Doe", new Date(1996, 12, 5));

it does exactly what it should do: create a new Person object.

BUT

this is what i get when do foo in console:

foo
Object { name: "Jon Doe", bdate: Object, age: 20 }

when i click on bdate object i get:

month: undefined

how to fix? PLUS year is 1997 instead of 1996

EDIT:no it's not duplicate of getutcmonth, that problem is treating 12 AS 0, mine returns undefined for month

ANOTHER EDIT:huh, i guess it acually is duplicate :P still, can you help me?

adddff
  • 27
  • 1
  • 7

1 Answers1

0

Month is zero-based. So your Array offset is wrong, and the month must be increased/decreased.

function Person(firstname, lastname, birth) {
this.name = firstname + " " + lastname;
this.bdate = {
 year: birth.getFullYear(),
 day: birth.getDate(),
 month: "January,Febuary,March,April,May,June,July,August,September,October,November,December".split(",")[birth.getMonth()],
 monthnumber: birth.getMonth()+1,
 }
this.age = new Date().getFullYear() - birth.getFullYear();
}

var foo = new Person("Jon", "Doe", new Date(1996, 11, 5));
console.log(foo);
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • is there a way to always decrease/increase month? like `new Date(1996, 12, 5)` becomes `new Date(1996, 11, 5)`? – adddff Jun 03 '17 at 18:08
  • @adddff when you start from an existing Date, use setMonth for that; the set methods for the components that make up the date have taking account of "overflow" build in. – CBroe Jun 03 '17 at 18:12
  • @adddff you could pass the values instead of the Date object, then generate the date in the constructor with offset – Jonas Wilms Jun 03 '17 at 18:22
  • @cbroe this does not relate to the question. setMonth(12); will not set month to december... – Jonas Wilms Jun 03 '17 at 18:23
  • @Jonasw that was in regard to adddff's comment. If they do not want to do proper validation of their input data at some point (sounds like they're looking for a way to avoid that), then setDate(12) will get you January of the next year automatically. Whether that helps them and would be the best way to go (I'd vote in favor of proper validation), is up to them. – CBroe Jun 03 '17 at 18:27
  • Subtracting the year does not give an accurate age, see [*Calculate age in JavaScript*](https://stackoverflow.com/questions/4060004/calculate-age-in-javascript). – RobG Jun 04 '17 at 05:15