คู่มือนี้สอนตั้งค่าวันที่/เวลาใน Linux ด้วยคำสั่ง date และซิงค์กับ NTP Server ผ่านอินเทอร์เน็ต
1. ดูวันที่/เวลาปัจจุบัน
date
# Mon Dec 22 22:35:58 IST 2008
2. ตั้งค่าด้วย date -s (Manual)
# รูปแบบ: "DD MON YYYY HH:MM:SS"
date -s "25 DEC 2008 13:45:00"
# Thu Dec 25 13:45:02 IST 2008
# รูปแบบอื่น
date +%Y%m%d -s "20081225"
date -s "2008-12-25 13:45:00"
3. Date Formatting (Format Specifiers)
| Specifier | ค่า | ตัวอย่าง |
%Y | Year (4 digits) | 2024 |
%m | Month (01-12) | 12 |
%d | Day (01-31) | 25 |
%H | Hour (00-23) | 13 |
%M | Minute (00-59) | 45 |
%S | Second (00-59) | 00 |
%A | Weekday Full | Thursday |
%a | Weekday Abbr | Thu |
%B | Month Full | December |
%b | Month Abbr | Dec |
%F | %Y-%m-%d | 2024-12-25 |
%T | %H:%M:%S | 13:45:00 |
ตัวอย่าง Format
date +"%Y-%m-%d %H:%M:%S"
# 2024-12-25 13:45:00
date +"%A, %B %d, %Y"
# Thursday, December 25, 2024
4. Relative Date (ภาษาธรรมชาติ)
date --date="yesterday"
date --date="tomorrow"
date --date="last month"
date --date="next month"
date --date="5 days ago"
date --date="7 days"
date --date="next Saturday"
date --date="2 years 3 months 4 days"
5. NTP (Network Time Protocol) - ซิงค์เวลาอัตโนมัติ
ติดตั้ง
# Ubuntu/Debian
sudo apt install ntpdate ntp
# หรือ systemd-timesyncd (built-in)
sudo apt install systemd-timesyncd
# CentOS/RHEL/Fedora
sudo dnf install ntp chrony
ตั้งค่า NTP Server
# แก้ไข /etc/ntp.conf (ntp classic)
server pool.ntp.org iburst
server 0.pool.ntp.org iburst
server 1.pool.ntp.org iburst
server 2.pool.ntp.org iburst
# หรือ /etc/chrony.conf (chrony - แนะนำใหม่)
pool pool.ntp.org iburst
# หรือ /etc/systemd/timesyncd.conf (systemd-timesyncd)
NTP=pool.ntp.org
FallbackNTP=time.google.com
เริ่มใช้งานและซิงค์
# systemd-timesyncd (ง่ายที่สุด)
sudo systemctl enable --now systemd-timesyncd
sudo timedatectl set-ntp true
# chrony
sudo systemctl enable --now chronyd
chronyc sources
chronyc tracking
# ntp classic
sudo systemctl enable --now ntpd
ntpdate pool.ntp.org
Timezone
# ดู Timezone ปัจจุบัน
timedatectl
# เปลี่ยน Timezone
timedatectl set-timezone Asia/Bangkok
# หรือ
ln -sf /usr/share/zoneinfo/Asia/Bangkok /etc/localtime
Hardware Clock (RTC)
# Sync System → Hardware
hwclock --systohc
# Sync Hardware → System
hwclock --hctosys
# ตั้งค่า Hardware Clock ใช้ UTC (แนะนำ)
timedatectl set-local-rtc 0
การใช้ NTP (systemd-timesyncd/chrony) เป็นวิธีมาตรฐาน สะดวก และแม่นยำ สำหรับ Production Server