JavaScript에서는 toLocaleString() 메서드의 timeZone 옵션을 활용하면 특정 지역의 시간대를 손쉽게 지정할 수 있습니다. 이를 이용해 아시아와 미국 각각의 날짜 및 시간을 표시할 수 있습니다.
아시아 시간대 표시하기
아시아 시간대(예: 인도 콜카타)를 기준으로 현재 날짜와 시간을 가져오려면 다음과 같이 작성합니다.
var todayDateTime = new Date().toLocaleString("en-US", {timeZone: "Asia/Kolkata"});미국 시간대 표시하기
미국 시간대(예: 뉴욕)를 기준으로 현재 날짜와 시간을 가져오려면 아래 코드를 사용합니다.
var americaDateTime = new Date().toLocaleString("en-US", {timeZone: "America/New_York"});전체 예제 코드
두 시간대의 결과를 함께 확인할 수 있는 완성된 예제입니다.
var todayDateTime = new Date().toLocaleString("en-US", {timeZone: "Asia/Kolkata"});
todayDateTime = new Date(todayDateTime);
console.log("The Asia Date time is=");
console.log(todayDateTime)
var americaDateTime = new Date().toLocaleString("en-US", {timeZone: "America/New_York"});
americaDateTime = new Date(americaDateTime);
console.log("The America Date time is=");
console.log(americaDateTime);프로그램 실행 방법
위 프로그램을 실행하려면 Node.js 환경에서 다음 명령어를 입력합니다.
node fileName.js
여기서는 파일 이름이 demo193.js라고 가정합니다.
실행 결과
위 코드를 실행하면 다음과 같은 출력 결과를 얻을 수 있습니다.
PS C:\Users\Amit\javascript-code> node demo193.js The Asia Date time is= 2020-08-08T08:44:50.000Z The America Date time is= 2020-08-07T23:14:50.000Z
출력 결과에서 볼 수 있듯이, 동일한 순간이라도 시간대에 따라 아시아와 미국의 날짜와 시간이 서로 다르게 표시되는 것을 확인할 수 있습니다. timeZone 옵션에는 IANA 시간대 이름(예: Asia/Seoul, America/Los_Angeles)을 자유롭게 지정할 수 있으므로, 다양한 지역의 현지 시간을 손쉽게 처리할 수 있습니다.