Linux時間と日付に関するプログラミング


すべてのunixシステムは同じ時間と日付の起点を使用しています:グリニッジ時間(GMT)1970年1月1日午前0時
時間は予め定義されたタイプtimeを通過する.tはlinuxシステムでは長整数型で処理されます.timeに含める.h中.
#include
time_t time(time_t *tloc);
time関数により、紀元から現在までの秒数を返す最下位の時間値が得られます.tlocが空のポインタでない場合、time関数は戻り値をtlocポインタが指す位置に書き込む.
#include <time.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

int main()
{
    int i;
    time_t the_time;

    for(i = 1; i <= 10; i++) {
        the_time = time((time_t *)0);
        printf("The time is %ld
", the_time); sleep(2); } exit(0); }

#include
double difftime(time_t time1,time_t time2);
difftime関数は、2つの時間値の差を計算し、time 1-time 2の値を浮動小数点数として返します.
より意味のある時間と日付を提供するには、時間値を読み取り可能な時間と日付に変換する必要があります.いくつかの標準関数があります.
#include
struct tm *gmtime(const time_t timeval);
tm構造は、以下に示すメンバーとして定義される
int tm_sec;                  /* Seconds.     [0-60] (1 leap second) */
int tm_min;                  /* Minutes.     [0-59] */
int tm_hour;                 /* Hours.       [0-23] */
int tm_mday;                 /* Day.         [1-31] */
int tm_mon;                  /* Month.       [0-11] */
int tm_year;                 /* Year - 1900. */
int tm_wday;                 /* Day of week. [0-6] */
int tm_yday;                 /* Days in year.[0-365] */
int tm_isdst;/*サマータイムかどうか*/
次のgmtime.c tm構造gmtimeによる現在の時刻と日付の印刷
#include <time.h>
#include <stdio.h>
#include <stdlib.h>

int main()
{
    struct tm *tm_ptr;
    time_t the_time;

    (void) time(&the_time);
    tm_ptr = gmtime(&the_time);

    printf("Raw time is %ld
", the_time); printf("gmtime gives:
"); printf("date: %02d/%02d/%02d
", tm_ptr->tm_year, tm_ptr->tm_mon+1, tm_ptr->tm_mday); printf("time: %02d:%02d:%02d
", tm_ptr->tm_hour, tm_ptr->tm_min, tm_ptr->tm_sec); exit(0); }

ローカル時間を表示するにはlocaltime関数を使用する必要があります
#include
struct tm *localtime(const time_t *timaval);
分解されたtm構造を元のtimeに再変換するにはt時間値、mktime関数を使用できます.
#include
time_t mktime(struct tm *timeptr);
構造tm構造がtime_を表すことができない場合tの値はmktimeですが-1
より友好的な時間と日付を得るために、dateコマンド出力のようにします.asctime関数とctime関数を使用できます.
#include
char *asctime(const struct tm *timeptr);
char *ctime(struct time_t *timeval);
#include <time.h>
#include <stdio.h>
#include <stdlib.h>

int main()
{
    time_t timeval;

    (void)time(&timeval);
    printf("The date is: %s", ctime(&timeval));
    exit(0);
}