0

i have the problem, that i get a wront time if i try to calculate it. Why? what did i wrong? it's not the biggest problem, because i can also substract -1 on each parts but its confusing me it would be cool to know why javascript calculate that as it did. oO thx

var listDaten = [
{
  jahre:   ['2000','2001'],
  monate:  ['12','9'], //12-09(so)
  tage:    ['28','2'], //248
}]
console.log("DatumA:" + new Date(2001,09,02) ) 
// wrong has to 02 sep 2001
console.log("DatumB:" + new Date(listDaten[0].jahre[1],listDaten[0].monate[1],listDaten[0].tage[1]) )
// wrong has to 02 sep 2001
console.log("DatumC:" + new Date(2000,12,28) )
// wrong has to 28 dec 2000
console.log("DatumD:" + new Date(listDaten[0].jahre[0],listDaten[0].monate[0],listDaten[0].tage[0]) )
// wrong has to 28 dec 2000
Eduard Tester
  • 151
  • 11
  • 2
    [Don't do maths with dates](https://codeblog.jonskeet.uk/2010/12/01/the-joys-of-date-time-arithmetic/). But if you absolute have to, _don't roll your own code_. You're using Javascript: use [moment.js](https://momentjs.com/) and rely on well tested, edge-case-aware code to do what needs to be done. – Mike 'Pomax' Kamermans Aug 08 '19 at 22:28
  • @Mike'Pomax'Kamermans hi. thx but why i dont have to use it? could you explain a bit? its more dangerouse to use an script which i can't proof well if that code makes more security issues in my system. and really its hard to read the codes from different source. – Eduard Tester Aug 08 '19 at 22:38
  • @EduardTester, date math is complex in levels that local, single developments should not, could not, will not reliably be performed. Have you considered how you'll calculate leap years in Brazil? Or the ghost leap seconds Google implemented in their clocks? :) – Eric Wu Aug 08 '19 at 22:54
  • It is most certainly not "more dangerous" to use a datetime library that millions of people trust, use, and rely on, on a daily basis because date maths is _incredibly hard_. Which is why any sensible dev will use a reliable, trustworthy library to do that job for them. – Mike 'Pomax' Kamermans Aug 08 '19 at 23:29

1 Answers1

3

The javascript new Date() function has the following syntax options, as per MDN:

new Date(); // returns the current system date
new Date(value); // expect milliseconds / timestamp
new Date(dateString); // expects a date string such as "1/1/2019"
new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]]); // expect parts of the date

In your case, you are using the last option, which expect a monthIndex, not a month nomber - as the second argument. Javascript month index is zero-based, hence the 1 month offset.

ISAE
  • 519
  • 4
  • 12