系統時間與硬體時間:系統時間就是我們執行 date 看到的時間,Linux 下所有的時間呼叫(除了直接存取硬體的指令)都用它。硬體時間則是主機板 BIOS 中的時間,由主機板電池供電維持,開機時系統會讀取它並據以設定系統時間(這個過程可能存在時區換算,視系統與設定而定)。
UTC 與本地時間:UTC(Coordinated Universal Time,協調世界時)在一般精度下等同 GMT。本地時間則因時區而異,換算公式為「本地時間 = UTC + 時區」,東為正、西為負。以中國為例,本地時間使用北京時間,在 Linux 上就是 CST(China Standard Time,注意美國中部標準時間也縮寫為 CST,兩者不同),時區為東八區,因此 CST = UTC + 8 小時。
下圖正好驗證了 CST = UTC + 時區的關係:

系統時間 date:直接執行 date 得到本地時間,加 -u 則顯示 UTC 時間。設定系統時間的格式為 #date 月日時分年.秒。

硬體時間 hwclock:直接執行 hwclock 顯示的未必是 BIOS 中的時間——若設定檔啟用了 UTC(UTC=true),顯示的是經過時區換算的時間;加上 --localtime 才會得到 BIOS 中的實際時間。設定硬體時間的格式為 hwclock --set --date="月/日/年 時:分:秒"。

更多細節可用 man、help 查閱。
1. uptime 命令

2. 查看 /proc/uptime:第一個數字即系統已運行的秒數,可用 date 反推啟動時間:
date -d "$(awk -F. '{print $1}' /proc/uptime) second ago" +"%Y-%m-%d %H:%M:%S"

3. 換算成「天/時/分/秒」的易讀格式:
cat /proc/uptime | awk -F. '{run_days=$1/86400; run_hour=($1%86400)/3600; run_minute=($1%3600)/60; run_second=$1%60; printf("系統已運行:%d天%d時%d分%d秒\n", run_days, run_hour, run_minute, run_second)}'

4. who 命令:who -b 查看最後一次系統啟動的時間。

5. last reboot:查看 Linux 最後一次啟動時間。

6. top、w:這兩個指令也能順帶看到時間資訊。


時間對作業系統至關重要,從內核到應用層,時間的表達方式與精度各不相同。Linux 內核用一個名為 jiffies 的常量來計算時間滴答數;應用層則可透過 time()、localtime() 等函數,藉由 tm 結構取得系統時間。以 3.0.35 內核為例,tm 結構如下:
struct tm {
int tm_sec; /* 秒 - [0,59] */
int tm_min; /* 分 - [0,59] */
int tm_hour; /* 時 - [0,23] */
int tm_mday; /* 日 - [1,31] */
int tm_mon; /* 月(0 代表一月)- [0,11] */
int tm_year; /* 年,等於實際年份減 1900 */
int tm_wday; /* 星期 - [0,6],0 代表週日 */
int tm_yday; /* 一年中的第幾天 - [0,365] */
int tm_isdst; /* 夏令時標識 */
};

程式中常用的函數:time() 取得日曆時間(從某個標準時間點到現在的秒數,在任何時區下同一時刻都是相同值);localtime() 把日曆時間轉為本地時間;asctime() 則把 tm 結構轉成 "Www Mmm dd hh:mm:ss yyyy" 格式的字串。
完整範例如下:
#include <stdio.h>
#include <sys/sysinfo.h>
#include <time.h>
#include <errno.h>
int print_system_boot_time() {
struct sysinfo info;
struct tm *ptm = NULL;
time_t cur_time = 0;
if (sysinfo(&info)) {
fprintf(stderr, "Failed to get sysinfo, errno:%u, reason:%s\n", errno, strerror(errno));
}
time(&cur_time);
ptm = localtime(&cur_time);
int year = ptm->tm_year + 1900;
int month = ptm->tm_mon + 1;
int day = ptm->tm_mday;
int wday = ptm->tm_wday;
int hour = ptm->tm_hour;
int min = ptm->tm_min;
int sec = ptm->tm_sec;
printf("The current date: %d-%-.2d-%d 星期%d %d:%.2d:%.2d\n", year, month, day, wday, hour, min, sec);
printf("The current date is %s", asctime(ptm));
return 0;
}
int main(int argc, char **argv) {
if (print_system_boot_time() != 0) return -1;
return 0;
}
