JavaScript

new Date() timezone 적용하기

pocket.dev 2024. 4. 10. 21:11
반응형

 

 

JS에서 new Date()를 이용해서 현재 시각을 콘솔에 찍어보면, toLocaleString을 적용했을 때와 9시간 차이가 나는 것을 확인할 수 있다. 이것은 한국 시간이 UTC보다 9시간 빠른 시간대이기 때문이다. 

const now = new Date();
console.log(now.toLocaleString()); // 4/10/2024, 8:57:11 PM => 현재 한국 시간
console.log(now); // 2024-04-10T11:57:11.268Z => ISO 8601

 

JS new Date()는 getTimezoneOffset이라는 함수를 지원하는데, 이것은 현재 타임존 offset을 분 단위로 제공한다. 한국의 경우 -540분을 해야 UTC와 같은 시간이 되기 때문에 getTimezoneOffset 함수 호출 시에 -540을 결과값으로 받는다.

* -540분 = -9시간 * 60분

const timezoneOffset = new Date().getTimezoneOffset();
console.log(timezoneOffset); // -540 = -9시간 * 60분

 

이렇게 얻은 offset을 우리는 milliseconds 단위를 적용해서 new Date()에 다시 적용시켜야 하므로, 받은 offset을 아래 코드처럼 ms 단위로 바꿔준다.

* -32400000ms = -540분 * 60초 * 1000ms

const oneSecondInMillisecond = 1000; // 1초는 1000ms
const oneMinuteInSecond = 60; // 1분은 60초
const timezoneOffsetToMilliseconds = timezoneOffset * (oneMinuteInSecond * oneSecondInMillisecond);
console.log(timezoneOffsetToMilliseconds); // -32400000

 

현재 시각에 위에서 구했던 timezone offset을 적용해보면, 현재 한국 시간대가 적용된 결과물을 확인할 수 있다. console을 보면 UTC 시간과 timezone이 적용된 시각이 9시간 차이나는 것을 확인할 수 있다.

const nowInTimezone = new Date(Date.now() - timezoneOffsetToMilliseconds);
const nowIsoString = nowInTimezone.toISOString();
console.log(nowInTimezone); // 2024-04-10T20:57:11.272Z
console.log(nowIsoString); // 2024-04-10T20:57:11.272Z
console.log(now); // 2024-04-10T11:57:11.268Z => timezone offset이 적용되지 않은 UTC 시각

 

만약 시간 부분을 자르고 날짜 부분만 사용하고 싶다면 slice 함수를 써서 string을 잘라내면 된다.

const nowInString = nowIsoString.slice(0, 10);
console.log(nowInString); // 2024-04-10

 

 

 

 

참조: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTimezoneOffset