Linux的時間有分成二種,一種是「硬體時間」由BIOS(或CMOS)所負責,另一種為「系統時間」由Linux負責,系統時間在系統開機後讀取硬體時間後,再由Linux管理時間。

date 日期時間指令
輸入date後若不加參數系統會回傳系統時間。

$ date
Tue May 2 14:57:04 UTC 2017
Mon Aug 14 07:13:04 UTC 2017
Mon Aug 14 07:13:04 UTC 2017
Mon Aug 14 07:13:04 UTC 2017

也可以設定參數使系統只回傳所需要的值

時間變數
%Y 年份
%m 月份
%d
%H
%M
%S

僅回傳年份

$ date %Y
2017

設定時間 -s

$ sudo date -s "20170502 1500"
Tue May 2 15:00:00 UTC 2017

時區檔案
Linux系統皆有設定的預設時區,系統時區檔案位於/etc/localtime
/usr/share/zoneinfo/目錄下存放了各個國家與地區所屬的時區檔案,時區檔案/etc/localtime就是連結到/usr/share/zoneinfo/Asia/Taipei

ubuntu更換時區

$ sudo dpkg-reconfigure tzdata

即可依地地選擇城市

timezone.JPG

Current default time zone: 'Asia/Taipei'
Local time is now:      Mon Aug 14 15:48:47 CST 2017.
Universal Time is now:  Mon Aug 14 07:48:47 UTC 2017.

若是想使用非互動模式(none interactive)設定時區可使用timedatectl

設定時區為UTC

$ sudo timedatectl set-timezone UTC

列出所有時區

$ timedatectl list-timezones

列出所有時區後會發現時區檔實在太多了(425個),我們可用grep尋找所在的地區以取得時區正確的名稱

列出所有亞洲時區

$timedatectl list-timezones | grep Asia

設定時區為東京(Tokyo)

$ date                                       #設定前先查看目前時間
Mon Aug 14 08:59:19 CST 2017
$ sudo timedatectl set-timezone Asia/Tokyo   #將時區設為東京時區

$ date                                       #查看設定後時區
Mon Aug 147 09:59:43 JST 2017

ntpdate 網路校時
語法:ntpdate <ntp server>

$sudo ntpdate watch.stdtime.gov.tw
2 May 14:37:09 ntpdate[18991]: the NTP socket is in use, exiting
hwclock 硬體(BIOS)時間
hwclock常用參數
參數 說明
-h 顯示help文件
-r 顯示目前硬體時間(預設參數)
-s 將硬體時間寫入系統時間
-w 將系統時間寫入硬體時間

 

$ hwclock      #不加參數回傳目前硬體時間(與-r同效果)
Tue May 2 15:03:12 UTC 2017  .265809 seconds
$ hwclock -r
Tue May 2 15:03:12 UTC 2017 .394674 seconds
$ sudo date -s "20160812 1200"  #先將系統時間更改
Fri Aug 12 12:00:00 UTC 2016
$ sudo hwclock -s;date    #將硬體時間寫入系統時間後再查看目前系統時間
Tue May 2 15:04:24 UTC 2017              #系統時間已被改寫
$ sudo ntpdate watch.stdtime.gov.tw;sudo hwclock -w;hwclock  #使用ndpdate校時後將系統時間寫入硬體時間並回傳目前硬體時間
2 May 15:06:29 ntpdate[18991]: the NTP socket is in use, exiting
Tue May 2 15:06:30 UTC 2017 .271364 seconds    #硬體時間已更新

 


參考資料:
阿舍的隨手記記、隨手寫寫...: Ubuntu 用指令設定和變更時區
Linux安全網-linux hwclock命令参数及用法详解--linux显示/设置硬件时钟命令
Ask ubuntu-How to change time-zone settings from the command line
通達人驛站-RTC hwclock 和 date 系統時間

arrow
arrow

    小必 發表在 痞客邦 留言(0) 人氣()