-1

I am using typescript (Angular 5) and I have the following code:

let date = new Date(2018, 8, 17, 14, 0);

I expect "Fri Aug 17 2018 14:00:00 GMT-0400 (Eastern Daylight Time)" as the result, but instead this is what it actually returns:

Mon Sep 17 2018 14:00:00 GMT-0400 (Eastern Daylight Time)

As you can see it adds a month to the date. I've fixed it by subtracting like the following code:

let date = new Date(2018, 8 - 1, 17, 14, 0);

My question is why is this happening? Any idea? Is there any other way to fix this?

Erfan
  • 437
  • 5
  • 9

2 Answers2

7

This is not Angular-related, it's just how JavaScript's Date works. Months are zero-based: January is 0, December is 11.

Lazar Ljubenović
  • 18,976
  • 10
  • 56
  • 91
0

Javascript Date object counts months from 0

from "W3Schools"

JavaScript counts months from 0 to 11. January is 0. December is 11.

https://www.w3schools.com/js/js_dates.asp

So just set 7 instead of 8

Tzook Bar Noy
  • 11,337
  • 14
  • 51
  • 82