1

I got a function with which I want to sort the blog posts after month.

function sortBlogPostsAfterMonth(blogData) {
  console.log(blogData[0].createdAt);
  var blogDateFormat = new Date(blogData[0].createdAt);
  console.log(blogDateFormat.getMonth());
}

the output in the console in the browser is this.

2013-11-24T11:32:29.023Z main.js:140
10

Why I get as month 10 and not 11?

Nice greetings

user2244925
  • 2,314
  • 3
  • 14
  • 11
  • the underlying reason is programming language starts index from 0 , means January is not 1 but 0 – Sarath Nov 24 '13 at 12:30
  • possible duplicate of [Why this operation with date (number of days between 2 dates) return this value?](http://stackoverflow.com/questions/7571977/why-this-operation-with-date-number-of-days-between-2-dates-return-this-value) – Qantas 94 Heavy Nov 24 '13 at 12:36

3 Answers3

2

By default javascript month starts from 0.You need to increement it by one.Try this:

console.log(blogDateFormat.getMonth()+1);
Joke_Sense10
  • 5,341
  • 2
  • 18
  • 22
1

That's how JS months work. They start at 0.

See month on https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#Parameters

Rudie
  • 52,220
  • 42
  • 131
  • 173
1

Javascript dates are . . . confusing at best (broken at worst). While days and years are as is (they start at 1), months are zero-indexed for some reason. Read more here: http://www.w3schools.com/jsref/jsref_getmonth.asp

tandrewnichols
  • 3,456
  • 1
  • 28
  • 33
  • But when I do blogDateFormat.getYear() I get 113 :x so this is broken too? – user2244925 Nov 24 '13 at 12:37
  • getYear() is deprecated. (And indeed, it DOES return 113. Probably a relic of the Y2K bug.) Use getFullYear() instead (returns 2013). You can check out all the Date methods here: http://www.w3schools.com/jsref/jsref_obj_date.asp – tandrewnichols Nov 24 '13 at 16:42