Why is the numbering of the months of the Date object starting at zero?

11

For example:

var data:Date = new Date();
trace(data.month); //Supondo que o mês seja Janeiro: 0

I'd like some details as I know it's not just in ActionScript and Javascript that this happens. Why not simplify the month counter so that in a conversion it is easy to understand, getting the numbers returned exactly like the months of the year (January = 1, February = 2, March = 3)?

Because we always have to decrease 1:

var dataStr:String = "28/04/2014";
var data:Date = new Date(dataStr.substr(6,4), (dataStr.substr(3,2)-1), dataStr.substr(0,2), 0, 0, 0);
trace(data.month); //3

Why does this happen?

    
asked by anonymous 28.04.2014 / 15:00

2 answers

5

This happens because every list / enum / counters / arrays, per convention start at 0

So it's ... understand that they remain 12 months, only they will go from 0 to 11, January to December.

If you want them to represent exactly the month you want, just add +1 .

If you create a list in javascript .

var arrayLista = [];
arrayLista.push("First");

If you have a debugger or something, you can see that the structure of this Array starts as follows:

arrayLista = { [0] => "First" }

If you increase it again with push , you'll see something like this:

arrayLista = { [0] => "First", [1] = "Second" }
    
28.04.2014 / 15:28
3

The reason why the months of the year start from scratch is a major flaw in the Java Date API project and, in my opinion, it occurs in other languages as well, such as Javascript.

This is probably a result of using an internal vector or internal use in the JVM of C ++ APIs, as noted in this SO issue , which led Sun to choose zero as the base month index.

I say that it was a project failure because it's no wonder that every week, whether at work or in forums, I come across a problem caused by a misunderstanding by the developer. Myself, knowing that, I fell into the same trick sometimes.

It's totally counterintuitive. For example, you receive in an input the text 2014-04-28 and it does a parse for date using the yyyy-MM-dd pattern. Then you have to print the month and see the 3 value. In my first experience with this I made sure it was a bug in my program. The same thing happened to several colleagues.

However, the difference is that in other languages like Javascript the formatting of parse dates is not as frequent or necessary as in back end languages.

>     
28.04.2014 / 16:40