구조체
구조체 tm
#include <time.h>
struct tm {
int tm_sec;
int tm_min;
int tm_hour;
int tm_mday;
int tm_mon;
int tm_year;
int tm_wday;
int tm_yday;
int tm_isdst;
};
구조체 timeval
struct timeval {
time_t tv_sec; /* 초 (seconds) */
suseconds_t tv_usec; /* 마이크로초 (microseconds) */
};
예제
#include <stdio.h>
#include <sys/time.h>
int main() {
struct timeval tv;
gettimeofday(&tv, NULL);
long long timestamp = (long long)tv.tv_sec * 1000 + tv.tv_usec / 1000;
printf("시간 (13자리 숫자): %lld\n", timestamp);
return 0;
}
---------------------결과-------------------------
시간 (13자리 숫자): 1719915305123
--------------------------------------------------
이 값은 밀리초 단위의 Unix Timestamp
이 결과를 사람이 볼 수 있도록 변경해줘야한다.
gettimeofday() , tm구조체와 tm 구조체 포인터로 로 현재 시간 가져오기
#include <stdio.h>
#include <sys/time.h>
#include <time.h>
int main() {
struct timeval tv;
struct tm tmr, *itime;
// 현재 시간을 가져옴
gettimeofday(&tv, NULL);
// 초 값을 변환하여 사람이 읽을 수 있는 형식으로 저장
itime = localtime_r(&tv.tv_sec, &tmr);
printf("원래 tv.tv_sec 값: %ld\n", tv.tv_sec);
printf("변환된 시간: %04d-%02d-%02d %02d:%02d:%02d\n",
itime->tm_year + 1900, itime->tm_mon + 1, itime->tm_mday,
itime->tm_hour, itime->tm_min, itime->tm_sec);
return 0;
}
---------------------결과-------------------------
원래 tv.tv_sec 값: 1719915305
변환된 시간: 2025-03-05 15:15:05
--------------------------------------------------
gettimeofday() : 현재 시간을 struct timeval 형식으로 반환하고 밀리초 단위의 시간 정보를 제공한다.
rm구조체 포인터 = localtime_r(&tv.tv_sec, &tm구조체);
localtime_r()가 하는 일은 숫자로 된 초를 사람이 읽을 수 있는 시간으로 변환하는 것
localtime_r() 함수의 동작 과정
1. tv.tv_sec 값 (Epoch Time)
gettimeofday(&tv, NULL); 실행 후, tv.tv_sec에는 1970년 1월 1일 00:00:00 UTC부터 경과한 초 단위의 숫자가 저장
tv.tv_sec = 1719915305;
2. localtime_r() 호출 과정
itime = localtime_r(&tv.tv_sec, &tmr);
tv.tv_sec = 1719915305을 struct tm 형식의 tmr로 변환
tmr 구조체 내부에 연-월-일 시:분:초가 변환된 tmr의 주소를 itime에 반환
-> tmr에는 다음과 같은 값이 들어가게 됨
tmr.tm_year = 2025 - 1900; // 연도 (1900 기준)
tmr.tm_mon = 3 - 1; // 월 (0부터 시작)
tmr.tm_mday = 5; // 일
tmr.tm_hour = 15; // 시
tmr.tm_min = 15; // 분
tmr.tm_sec = 5; // 초
정리
- tv.tv_sec은 초 단위로 된 숫자(1970년 이후 경과 시간)
- localtime_r()는 이 값을 **연-월-일 시:분:초 구조체(tmr)**로 변환
- 변환된 값이 tmr에 저장되고, itime가 이를 가리킴
- 이제 tmr.tm_sec, tmr.tm_min, tmr.tm_hour 등을 사용하여 원하는 정보를 얻을 수 있음
tv.tv_sec 값이 의미하는 것
tv.tv_sec = 1719915305; 는 다음을 의미합니다:
- 1970년 1월 1일 00:00:00 UTC 부터
- 1719915305초가 지난 시점
- 이를 변환하면 2025년 3월 5일 15시 15분 05초 (KST 기준)
즉, 이 숫자 자체가 날짜·시간을 담고 있는 것은 아니지만, 변환하면 알 수 있음.
'그냥 C언어' 카테고리의 다른 글
[C언어] makefile (0) | 2025.03.07 |
---|