時刻の扱い

システム・プログラム

                                       電子・情報工学系
                                       新城 靖
                                       <yas@is.tsukuba.ac.jp>

このページは、次の URL にあります。
http://www.hlla.is.tsukuba.ac.jp/~yas/coins/syspro-2000/2000-04-24 /time.html
あるいは、次のページから手繰っていくこともできます。
http://www.hlla.is.tsukuba.ac.jp/~yas/coins/
http://www.is.tsukuba.ac.jp/~yas/index-j.html

■時刻の扱い

Unix では、カレンダーの時刻は、1970年1月1日0:00(GMT)からの秒数で表して いる。これを time_t (または clock_t )と表している。time_t の実体は、普 通、32ビットの整数である。

現在の時刻を取得するには、times() システム・コール(System V系)や gettimeofday() システム・コール (BSD系)を使う。

その秒数からカレンダーに便利な形式(struct tm)に変換するものが、 localtime() ライブラリ関数である。struct tm は、次のようなフィールドが ある。

struct    tm {
     int  tm_sec;   /* seconds after the minute - [0, 61] */
			 /* for leap seconds */
     int  tm_min;   /* minutes after the hour - [0, 59] */
     int  tm_hour;  /* hour since midnight - [0, 23] */
     int  tm_mday;  /* day of the month - [1, 31] */
     int  tm_mon;   /* months since January - [0, 11] */
     int  tm_year;  /* years since 1900 */
     int  tm_wday;  /* days since Sunday - [0, 6] */
     int  tm_yday;  /* days since January 1 - [0, 365] */
     int  tm_isdst; /* flag for alternate daylight */
			 /* savings time */
};

ctime(), strftime() などを使うと、文字列に変換してくれる。

逆に、struct tm から time_t を作る関数が mktime() ライブラリ関数である。

localtime() や mktime() は、TZ環境変数(Time Zone)を見ている。閏秒など が混じると単純には計算できない。

★練習問題22 ctime(3) の利用

date コマンドと似たプログラム(現在の時刻を表示するプログラム)を、 times(), gettimeofday(), ctime() などを使って作りなさい。

★練習問題22 localtime(3)、strftime(3) の利用

localtime(3)やstrftime(3)を使って、ctime() や dateコマンドとは異なる形 式で時刻の表示するプログラムを作りなさい。
↑[もどる] ←[4月17日] ・[4月24日] →[5月01日] [課題]
Last updated: 2000/04/23 02:04:04
Yasushi Shinjo / <yas@is.tsukuba.ac.jp>