1

I can get day no via current date like this, it's give me current result

const dateObject = new Date()
console.log(dateObject.getDay())

But When I try to day no of a specific date, I'm not getting actual answer

const dateObject = new Date(2018, 8, 5)
console.log(dateObject.getDay())

I expect 0 , as it's sunday of the week, but I got 3.

What is my fault or misunderstanding here? Thanks

bork
  • 1,556
  • 4
  • 21
  • 42
King Rayhan
  • 2,287
  • 3
  • 19
  • 23
  • Why would it be Sunday? The date you give is in _september_ because the type of Date constructor you used [expected months that start at 0](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) (there are lots of gotcha's when using Date. So you typically don't use Date directly for calendar "maths"). If you wanted August 5th, 2018, use `Date("2018-08-05")` or `Date(2018,7,5)` – Mike 'Pomax' Kamermans Aug 04 '18 at 17:34

3 Answers3

4

The monthIndex parameter in the Date constructor zero-based, so 8 is September, not August. getDay then correctly tells you that the fifth of September is a Wednesday.

See MDN for more: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#Parameters

There are enough bizarre oddities with JS dates that I just use MomentJS whenever I'm dealing with date/time values.

SomeKittens
  • 38,868
  • 19
  • 114
  • 143
1

In new Date(2018, 8, 5), month starts from 0 and not 1. Hence in your case it is not August but September.

Rishikesh Dhokare
  • 3,559
  • 23
  • 34
1

You are wrong with month index. Month mormally start with 0 index.

January = 0
February = 1
March = 2
April = 3
...
...
...
...

So August month's index number is 7.

You answer will be like this:

const dateObject = new Date(2018, 7, 5)
console.log(dateObject.getDay())
Enamul Haque
  • 144
  • 9