Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

แสดง Date Time โซนเอเชียและอเมริกาด้วย Date Object ใน JavaScript

วิธีทำ

ใช้ toLocaleString() พร้อมระบุ timeZone

Asia Time Zone:

var todayDateTime = new Date().toLocaleString("en-US", {timeZone: "Asia/Kolkata"});

America Time Zone:

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 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

คำอธิบาย

toLocaleString(locales, options) พร้อม timeZone ใน options รองรับ IANA time zones เช่น "Asia/Kolkata", "America/New_York", "Asia/Bangkok" แปลงเป็น Date object อีกครั้งเพื่อให้ได้ ISO format