Programming/Javascript, Typescript

[JavaScript] .getMonth() 메서드는 왜 zero-base일까?

리버김 2023. 7. 25.

.getMonth() 메서드란

 

const moonLanding = new Date('July 20, 69 00:20:18');

console.log(moonLanding.getMonth()); // (January gives 0)
// Expected output: 6

Date.prototype.getMonth() 메서드는 Date 객체의 월 값을 현지 시간에 맞춰 반환한다. 그런데 이 때 월은 0부터 시작한다.

 

월만 0부터 시작하는 이유는?

 

모든 Date관련 get 메서드가 zero-base라면 이상할 게 없다. 하지만 연, 일은 그렇지 않은데 월만 그런 것은 매우 이상하다.

사람에게 자연스럽지 않고 일관성도 없기 때문이다. 호기심이 발동했는데, JS의 아버지인 브랜든 아이크의 예전 트윗에서 답을 발견할 수 있었다.

 

 

브랜든 아이크: JS의 Date는 Java JDK 1.0의 java.util.Date의 복사본이다. Java와 비슷하게 만들고자 했다...우리는 "Java처럼 보이게 만들기"라는 관리자의 주문을 받았고, 데모를 만들 때까지는 열흘이 남아 있었다. 우리 고유의 Date API를 만들거나 Java의 것을 고칠 시간조차 없었던 것이다.

 

결론

 

그러니까 이렇게 월만 0부터 시작하는 날짜 관련 함수는 Java 개발자들로부터 비롯되었고, 더 정확하게는 Java와 비슷하도록 JavaScript를-신속하게-개발해 나가야 했던 JavaScript 개발자들의 상황에서 비롯된 것이라고 할 수 있다.

 

하지만 Java는 8버전부터 새로운 시간 패키지를 개발함으로써 이 문제를 뿌리 뽑았지만, JS는 무려 오늘까지도(...) 이 문제를 그대로 놔두고 있다. 의도적인 건지, 그냥 굳어진 대로 사용하기로 한 건지는 모르지만 개발할 때 주의하자!

 

Ref

 

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Date/getMonth

 

Date.prototype.getMonth() - JavaScript | MDN

getMonth() 메서드는 Date 객체의 월 값을 현지 시간에 맞춰 반환합니다. 월은 0부터 시작합니다.

developer.mozilla.org

https://stackoverflow.com/questions/2552483/why-does-the-month-argument-range-from-0-to-11-in-javascripts-date-constructor/41992352#41992352

 

Why does the month argument range from 0 to 11 in JavaScript's Date constructor?

When initializing a new Date object in JavaScript using the below call, I found out that the month argument counts starting from zero. new Date(2010, 3, 1); // that's the 1st April 2010! Why doe...

stackoverflow.com

 

반응형

댓글