C++ STL : <ctime> 헤더와 tm 구조체

김종민·2025년 2월 27일

C++

목록 보기
3/5

1. <ctime>

C++ 표준 라이브러리 중 하나로 시간과 날짜에 대한 타입과 함수들을 정의하고 있다.


2. 타입과 구조체

time_t

typedef /* 산술 유형 타입 (arithmetic type) */ time_t;

Unix Time(POSIX Time, Epoch Time)을 기준으로 몇 초가 지났는지 타임 스탬프를 표시한다.
정확히는 1970년 1월 1일 0시 0분 0초를 기준으로 삼는다.

tm

struct tm
{
    int tm_sec;   // seconds after the minute - [0, 60] including leap second // 윤초 포함
    int tm_min;   // minutes after the hour - [0, 59]
    int tm_hour;  // hours since midnight - [0, 23]
    int tm_mday;  // day of the month - [1, 31]
    int tm_mon;   // months since January - [0, 11]
    int tm_year;  // years since 1900
    int tm_wday;  // days since Sunday - [0, 6]
    int tm_yday;  // days since January 1 - [0, 365]
    int tm_isdst; // daylight savings time flag // 서머타임 적용 여부
};

leap second? : 시간 오차 보정을 위한 윤초

tm_year는 1900년을 기준으로 카운트하므로 현재 년도로 출력할 때는 1900을 더해야한다.
tm_mon은 1월을 기준으로 카운트하므로 1월 ~ 12월로 출력하려면 1을 더해야한다. (안 하면 0~11)


3. 함수

함수 정리된 링크

time() : 현재 시간(초) 구하기

문법

time_t time(time_t* timer);

timer 변수에 유닉스 타임으로 시간초를 할당하고 time 값 자체도 리턴한다.

예시

#include <iostream>
#include <ctime>
using namespace std;

int main() {
  time_t timer;
  cout << time(&timer)<< "\n";
  cout << timer;
  return 0;
}

출력

1740637567  // 리턴값이 있기 때문에 바로 출력 가능
1740637567  // 동일한 값이 timestamp에도 저장

📖
이 상태로는 현재 시간을 알아보기 어렵기 때문에 tm 구조체와 localtime() 함수 등으로 조정이 필요하다.


localtime() : 현재 시간에 맞는 tm 구조체를 생성

문법

struct tm* localtime(const time_t* timer);

timer의 시간을 기준으로 tm 구조체를 만들어 리턴한다.

예시

#include <iostream>
#include <ctime>
using namespace std;

int main() {
  time_t now;
  struct tm * date;

  time(&now);
  date = localtime(&now);

  cout << "Year: " << date->tm_year + 1900 << endl;  // + 1900
  cout << "Month: " << date->tm_mon + 1 << endl;	 // + 1
  cout << "Day: " << date->tm_mday << endl;
  cout << "Hour: " << date->tm_hour << endl;
  cout << "Min: " << date->tm_min;
 
  return 0;
}

출력

Year: 2025
Month: 2
Day: 27
Hour: 6
Min: 43

difftime() : 두 timer 간의 차이 구하기

문법

double difftime(time_t time1, time_t time0);

time0에서 time1까지 얼마나 지났는지(초)를 리턴한다.
시작 시간보다 끝 시간이 작다면 음수가 나올 수 있다.

예시

#include <iostream>
#include <ctime>
using namespace std;

int main() {
  struct tm date;
  time_t now;
  time_t before;

  // Create a timestamp for right now
  time(&now);

  // Create a timestamp for 5 hours ago
  date = *localtime(&now);
  date.tm_hour -= 5;
  before = mktime(&date);

  // Calculate the difference between the two timestamps in seconds
  cout << difftime(now, before);
  return 0;
}

출력

18000

mktime() : tm 구조체로 time_t 생성

문법

time_t mktime(struct tm* date);

tm 구조체인 date를 다시 초 단위인 time_t 값으로 리턴한다.

예시

#include <iostream>
#include <ctime>
using namespace std;

int main() {
  struct tm date;
  time_t timestamp;

  date.tm_year = 2023 - 1900; // Number of years since 1900
  date.tm_mon = 12 - 1; // Number of months since January
  date.tm_mday = 17;
  date.tm_hour = 12;
  date.tm_min = 30;
  date.tm_sec = 1;
  date.tm_isdst = -1;

  timestamp = mktime(&date);

  cout << timestamp;
  return 0;
}

출력

1702816201

ctime() : 시간초를 날짜 포맷 문자열로 변환

문법

char* ctime(const time_t* timer);

timer를 WWW MMM DD HH:mm:ss YYYY 형태의 문자열로 리턴한다.

예시

#include <iostream>
#include <ctime>
using namespace std;

int main() {
  time_t timestamp;
  time(&timestamp);
  cout << ctime(&timestamp);
  return 0;
}

출력

Thu Feb 27 14:03:08 2025

asctime() : tm 구조체를 날짜 포맷 문자열로 변환

문법

char* asctime(const struct tm* date);

date를 WWW MMM DD HH:mm:ss YYYY 형태의 문자열로 리턴한다.

예시

#include <iostream>
#include <ctime>
using namespace std;

int main() {
  time_t timestamp;
  time(&timestamp);
  struct tm * myTime = localtime(&timestamp);
  cout << asctime(myTime);
  return 0;
}

출력

Thu Feb 27 14:05:40 2025

참고 자료

https://www.w3schools.com/cpp/cpp_ref_ctime.asp
https://dev-astra.tistory.com/182

profile
정리와 기록

0개의 댓글