프로그래밍 언어 공부/C

시간 관련 라이브러리

CalebHong 2022. 1. 20. 11:58

종류

헤더 파일: time.h

 

1. 시간 계산

time: 현재 시간

clock: 시간 계산 함수

difftime: 두 시간 사이의 차이 계산

mktime: struct tm 구조체를 통해 epoch time을 구하는 함수

 

2. 시간 변환

asctime: 시간구조체를 문자로 변환

ctime: 시간변수를 문자로 변환

gmtime: UTC 시간으로 변환

localtime: 지역 시간으로 변환

strftime: 날짜와 시간으로 이루어진 문자열을 struct tm으로 변환

 

라이브러리 변수

stize_t: 부호 없는 정수형

clock_t: 프로세서 시간 저장 변수 타입

time_t: 캘린더 시간 저장 변수 타입

struct tm: 날짜, 시간 처리 구조체

관련 용어

Epock Time

- 1970년 01월 01일 00시 00분 00초를 기점으로 흐르는 시간

 

UTC Time

- 영국 그리니치 천문대(경도 0)를 기준으로 하는 세계의 표준 시간대

- UTC+9 : 한국 시간

 

Greenwich Mean Time, GMT

- 영국 런던을 기점으로 뉴질랜드 웰링턴을 종점으로 하는 협정 세계시

 

라이브러리 함수 활용

1. clock

 

2. time

 

3. difftime

#include <stdio.h>
#include <time.h>

int main()
{
    time_t start, end;
    char szInput [256];
    double dif;
    
    time(&start); // time_t 타입의 주소를 줌으로 현재 시간을 저장
    printf("Please, enter your name: ");
    gets(szIput);
    time(&end);
    dif = difftime(end, start); // 시간 차를 double 형으로 리턴됨
    printf("Hi %s. \n", szInput);
    printf("It took you %.2lf secounds to type your name. \n", dif);
    
    return 0;
}

 

4. ctime

#include <stdio.h>
#include <time.h>

int main(void)
{
    time_t current_time;
    
    time(&current time);
    
    printf("%ldn", current_time); // 출력 예: 1184746481
    printf(ctime(%current_time)); // 출력 예: Wed Jul 18 17:14:41 2027
    
    return 0;
}

 

5. strftime

#include <stdio.h>
#include <time.h>

int main(void)
{
    time_t rawtime;
    struct tm* timeinfo;
    char buffer [80];
    
    time(&rawtime);
    timeinfo = localtime(&rawtime);
    
    strftime(buffer, 80, "Now it's %l:%M%p.", timeinfo);
    puts(buffer); // 출력 예: Nowit's 03:21 PM.
    
    return 0;
}

 

6. localtime

 

7. asctime