'time()'에 해당되는 글 1건

  1. 2009.12.09 시간관련 함수/구조체 - time API on linux
Linux2009. 12. 9. 17:15

#include <time.h>

time_t time(time_t *t);
size_t strftime(char *s, size_t max, const char *format, const struct tm *tm);

char *asctime(const struct tm *tm);
char *asctime_r(const struct tm *tm, char *buf);
char *ctime(const time_t *timep);
char *ctime_r(const time_t *timep, char *buf);
struct tm *gmtime(const time_t *timep);
struct tm *gmtime_r(const time_t *timep, struct tm *result);
struct tm *localtime(const time_t *timep);
struct tm *localtime_r(const time_t *timep, struct tm *result);
time_t mktime(struct tm *tm);

struct tm
{
    int tm_hour;//     hour (0 - 23)
    int tm_isdst;//     Daylight saving time enabled (> 0), disabled (= 0), or unknown (< 0)
    int tm_mday;//     day of the month (1 - 31)
    int tm_min;//     minutes (0 - 59)
    int tm_mon;//     month (0 - 11, 0 = January)
    int tm_sec;//     seconds (0 - 59)
    int tm_wday;//     day of the week (0 - 6, 0 = Sunday)
    int tm_yday;//     day of the year (0 - 365)
    int tm_year;//     year since 1900
}

[링크 : http://en.wikipedia.org/wiki/Time.h] Time_t 구조체 내용
[링크 : http://en.wikipedia.org/wiki/Time_t]  Time_t 구조체 사용방법

[링크 : http://linux.die.net/man/3/strftime]
[링크 : http://linux.die.net/man/3/localtime]
[링크 : http://linux.die.net/man/3/mktime]

struct tm과 time_t 라는 타입은 시간에 사용된다.
mktime() 은 struct tm의 값으로 timt_t 형의 시간을 만들어 주고, time()은 현재의 시간을 반환해준다.(time_t *t = NULL)
localtime() 으로 time_t 형의 값으로 변환해준다.
strftime()은 sprintf와 비슷하게 time_t 형의 값을 받아 문자열로 시간을 나타내준다.

복잡하게 보이지만, 간단하게 예를 들자면,
int main(void)
{
    time_t     now;
    struct tm  tmtm;
    struct tm  *ts;
    char       buf[80];

    /* Get the current time */
    //now = time(NULL);
    tmtm.tm_year = 102;
    tmtm.tm_mon = 1;
    tmtm.tm_mday = 23;
    tmtm.tm_hour = 10;
    tmtm.tm_min = 12;
    tmtm.tm_sec = 51;
    now = mktime(&tmtm);

    /* Format and print the time, "ddd yyyy-mm-dd hh:mm:ss zzz" */
    ts = localtime(&now);
    strftime(buf, sizeof(buf), "%a %Y-%m-%d %H:%M:%S %Z", ts);
    printf("%s\n", buf);

    return 0;
}
결과는 아래와 같다.
 Sat 2002-02-23 10:12:51 KST
mktime()으로 원하는 시간과 날자를 넣고, (만약 주석된 time()을 풀면 현재 시간이 나온다)
localtime()을 통해서 time_t 형으로 변환하고
strftime()을 통해서 문자열로 출력을 한다.
만약에 요일이 궁금하다면 날자를 넣고, localtime() 한뒤 리턴되는 struct tm 의 값중 tm_wday 을 읽으면 된다.

[링크 : http://www.joinc.co.kr/modules/moniwiki/wiki.php/man/3/mktime]
Posted by 구차니