ปัญหา “วันที่” ใน Google Apps Script มักจะเกิดจาก Time Zone, Format, และ การรับ-ส่งค่าระหว่าง client ↔ server เดี๋ยวผมสรุปให้แบบใช้งานจริง พร้อมโค้ดแก้ครบจุดครับ
🔥 สาเหตุหลัก (ที่เจอบ่อยมาก)
- Time zone ไม่ตรง (เช่น Script = UTC แต่ไทย = GMT+7)
new Date()แสดงผลไม่ตรง format- HTML
<input type="datetime-local">ส่งค่าเป็น string (ไม่ใช่ Date) - Google Sheets เก็บเป็น Date แต่ Apps Script อ่านเป็น String/Number
✅ วิธีแก้แบบครบระบบ
1. ตั้ง Time Zone ให้เป็นไทยก่อน (สำคัญสุด)
ไปที่
Project Settings → Time zone → Asia/Bangkok
หรือกำหนดในโค้ด:
const TZ = 'Asia/Bangkok';
2. แปลงวันที่ให้เป็นรูปแบบไทย (ฝั่ง Server)
function formatThaiDate(date) {
return Utilities.formatDate(new Date(date), 'Asia/Bangkok', 'dd/MM/yyyy HH:mm');
}
3. รับค่าจาก <input type="datetime-local"> (ฝั่ง Client)
ค่าที่ได้จะเป็นแบบนี้:
2026-04-16T14:30
👉 ต้องแปลงก่อนส่งไป GAS:
const raw = document.getElementById("date").value;
const date = new Date(raw); // แปลงเป็น Date object
4. ส่งไป Apps Script แล้ว format
function saveData(data) {
const date = new Date(data.date);
const formatted = Utilities.formatDate(date, 'Asia/Bangkok', 'yyyy-MM-dd HH:mm:ss');
return formatted;
}
5. บันทึกลง Google Sheets แบบไม่เพี้ยน
sheet.appendRow([
new Date(), // เวลาปัจจุบัน
Utilities.formatDate(new Date(), 'Asia/Bangkok', 'dd/MM/yyyy HH:mm')
]);
6. แสดงผลเป็น พ.ศ. (แบบไทย)
function formatThaiFull(date) {
const d = new Date(date);
const year = d.getFullYear() + 543;
return Utilities.formatDate(d, 'Asia/Bangkok', `dd/MM/${year} HH:mm`);
}
7. ป้องกัน “เวลาเลื่อน +7 / -7 ชั่วโมง”
❌ ห้ามใช้แบบนี้:
new Date("2026-04-16 10:00") // ❌ เสี่ยงเพี้ยน
✅ ใช้แบบนี้:
new Date("2026-04-16T10:00") // ✔ ถูกต้อง
8. Debug เวลาเพี้ยน (เช็คจริง)
function testDate() {
const now = new Date();
Logger.log(now);
Logger.log(Utilities.formatDate(now, 'Asia/Bangkok', 'yyyy-MM-dd HH:mm:ss'));
}
🎯 สรุปแบบสั้น
- ตั้ง Time zone =
Asia/Bangkok - ใช้
Utilities.formatDate()ทุกครั้ง - รับค่าจาก input ต้อง
new Date()ก่อน - ใช้ format
yyyy-MM-ddTHH:mmตอนส่ง/รับ
🔴 ถ้าใช้ใน Browser (client JS)
👉 Utilities.formatDate ❌ ใช้ไม่ได้
✅ ใช้แบบนี้แทน:
function fmtDate(d) {
if (!d) return '-';
return new Date(d).toLocaleString('th-TH', {
timeZone: 'Asia/Bangkok',
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
hour12: false
}).replace(',', '');
}
🔥 เวอร์ชันสวย (format ไทย)
13/04/2026 17:30
💯 สรุป
| ที่ใช้ | วิธี |
|---|---|
| GAS (server) | Utilities.formatDate ✅ |
| Browser | toLocaleString + timeZone ✅ |
🚀 Pro Tip
ถ้าคุณทำ dashboard:
👉 แนะนำให้
-
server ส่งเป็น ISO (
new Date().toISOString()) - client เป็นคน format
👉 จะ:
- เร็วกว่า
- คุม timezone ง่ายกว่า
- scale ได้ดี