프로그래밍/리눅스
[C언어] time 사용법 - 시간 출력 포맷, 시간 / 문자열 변환
앗싸붕
2020. 11. 16. 11:31
728x90
반응형
시간 출력 (년월일, 시분초)
시간 출력에 관련한 simple example 을 공유합니다.
예제에 사용된 함수는 아래와 같습니다.
time()
time_t time(time_t *timeptr)
- 인자에 NULL 을 넘길 경우, 현재까지의 시간을 초 단위로 반환함.
localtime()
struct tm *localtime(const time_t *timeval);
- 초 단위 시간을 tm struct 에 담아서 반환. (년월일시분초 포맷화)
strptime()
char *strptime(const char *s, const char *format, struct tm *tm);
- 시간 문자열을 tm struct 로 변환하는 함수.
strftime()
size_t strftime(char *s, size_t maxsize, const char *format, const struct tm * timeptr);
- tm struct 로 포맷화 된 문자열을 만드는 함수.
#include <stdio.h>
#include <time.h>
void main (void)
{
time_t timer;
struct tm *t;
char date[32]={0,};
timer = time(NULL);
t = localtime(&timer);
sprintf(date, "%04d-%02d-%02d", t->tm_year +1900, t->tm_mon+1, t->tm_mday);
printf ("date: %s\n", date);
sprintf(date, "%02d:%02d:%02d", t->tm_hour, t->tm_min, t->tm_sec);
printf ("time: %s\n", date);
}
- 출력 결과
[jungfo time] gcc main.c
[jungfo time] ./a.out
date: 2020-11-16
time: 12:58:09
문자열을 시간으로 / 시간을 문자열으로
#include <stdio.h>
#include <time.h>
void main ()
{
struct tm t;
const char* date = "2019-10-21"; // 날짜 문자열: 2019년 10월 21일
const char* time = "18:16:24"; // 시간 문자열: 18시 16분 24초
char* ret=NULL;
char buf[256];
ret = strptime(date, "%Y-%m-%d", &t); // 날짜 문자열을 tm 구조체로
ret = strptime(time, "%H:%M:%S", &t); // 시간 문자열을 tm 구조체로
strftime(buf, sizeof(buf), "%Y년 %m월 %d일", &t); // tm 구조체에서 날짜를 buf 로
puts(buf);
strftime(buf, sizeof(buf), "%H:%M:%S", &t); // tm 구조체에서 시간을 buf 로
puts(buf);
}
출력 결과
[jungfo time] gcc main.c
[jungfo time] ./a.out
2019년 10월 21일
18:16:24
참고사항
struct tm 정의
struct tm {
int tm_sec; //초
int tm_min; //분
int tm_hour; //시
int tm_mday; //일
int tm_mon; //월(0부터 시작)
int tm_year; //1900년부터 흐른 년
int tm_wday; //요일(0부터 일요일)
int tm_yday; //현재 년부터 흐른 일수
int tm_isdst; //썸머타임 사용
};
728x90
반응형