16 diciembre 2010

Javascript Date.getYear vs Date.getFullYear

Curiositats del món de la programació informàtica, per no dir altres coses. És cert que sempre cal llegir bé les especificacions de les API, però ja se sap, les presses, la bona fe o altres ingerències no desitjades no ajuden a mantenir els bons costums. L'altre dia em vaig trobar amb un cas que em va fer ballar el cap (com dic per no haver llegit bé) amb el mètode getYear de l'objecte Date, que retorna l'any d'una data.

Segons la documentació:
This returns the year in the specified date according to universal time. The getYear is no longer used and has been replaced by the getFullYear method.

The value returned by getYear is the current year minus 1900. JavaScript 1.2 and earlier eturns either a 2-digit or 4-digit year, for example if the year is 2026, the value returned is 2026. So before testing this function make sure the version about the javascript version.

La punyeta és que el mètode no funciona de la mateixa manera segons la versió de javascript i/o el navegador que utilitzes, de manera que a vegades et pot retornar l'any en dues xifres i d'altres usant-ne quatre. ole!! ole !!

Com bé diu la docuementació, és molt millor usar el mètode getFullYear, i evitar-se maldecaps.


No hay comentarios: