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

วิธีตั้งค่าเวลาเป็น Timezone อื่นใน JavaScript

JavaScript ไม่สามารถเปลี่ยน System Time ได้ (เพื่อความปลอดภัย) แต่สามารถ คำนวณเวลาใน Timezone อื่น ได้จาก System Time ปัจจุบัน

ตัวอย่าง: แปลงเป็นเวลา Singapore (GMT+8)

<!DOCTYPE html>
<html>
  <body>
    <script>
      var date = new Date();
      document.write("Current: " + date);

      // แปลงเป็น UTC ก่อน
      var utc = date.getTime() + (date.getTimezoneOffset() * 60000);

      // Singapore = GMT+8
      var offset = 8;
      var singaporeTime = new Date(utc + (3600000 * offset));

      document.write("<br>Singapore Time: " + singaporeTime.toLocaleString());
    </script>
  </body>
</html>

ผลลัพธ์ตัวอย่าง

Current: Mon Jan 15 2024 10:30:00 GMT+0700 (Indochina Time)
Singapore Time: 15/1/2024, 11:30:00

วิธีทันสมัย: Intl.DateTimeFormat (แนะนำ)

const now = new Date();

// Format ตาม Timezone ที่ต้องการ
const singapore = new Intl.DateTimeFormat('en-SG', {
  timeZone: 'Asia/Singapore',
  year: 'numeric', month: '2-digit', day: '2-digit',
  hour: '2-digit', minute: '2-digit', second: '2-digit',
  hour12: false
}).format(now);

console.log(singapore); // "15/01/2024, 11:30:00"

// ได้เฉพาะส่วนเวลา
const timeOnly = new Intl.DateTimeFormat('en-SG', {
  timeZone: 'Asia/Singapore',
  hour: '2-digit', minute: '2-digit', second: '2-digit',
  hour12: false
}).format(now);

Timezone Database (IANA Time Zones)

ใช้ชื่อ Timezone มาตรฐาน IANA:

  • Asia/Bangkok (GMT+7)
  • Asia/Singapore (GMT+8)
  • Asia/Tokyo (GMT+9)
  • America/New_York (EST/EDT)
  • Europe/London (GMT/BST)
  • UTC

Library แนะนำสำหรับงาน Timezone ซับซ้อน

  • Luxon - ทันสมัย, Immutable, รองรับ IANA Timezones
  • date-fns-tz - Extension ของ date-fns
  • moment-timezone - Legacy (ใหญ่, ไม่ maintain แล้ว)

สรุป: ใช้ Intl.DateTimeFormat กับ timeZone option สำหรับการแสดงผล ใช้ Library สำหรับการคำนวณ/แปลงซับซ้อน