본문 바로가기

Language Proficiency/C++

날짜시간(YYYYMMDDHHMMSS) 문자열을 chrono의 time_point로 변환하기

문자열의 날짜시간 포맷(YYYYMMDDHHmmSS)을 std::chrono의 time_point로 변환해서 계산해야 하는 경우, 다음과 같이 변환 함수를 만들 수 있다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
std::chrono::system_clock::time_point CMyDateTime::convertStrToTimepoint(const std::string& p_sDate)
{
    //int tm_sec;     /* seconds after the minute - [0,59] */
    //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 */
 
    // p_sDate 파라미터는 년월일시분초로 전달됨(YYYYMMDDHHMMSS)
    std::tm date = {};
    date.tm_year = std::stoi(p_sDate.substr(04)) - 1900;
    date.tm_mon = std::stoi(p_sDate.substr(42)) - 1;
    date.tm_mday = std::stoi(p_sDate.substr(62));
    date.tm_hour = std::stoi(p_sDate.substr(82));
    date.tm_min = std::stoi(p_sDate.substr(102));
    date.tm_sec = std::stoi(p_sDate.substr(122));
 
    return std::chrono::system_clock::from_time_t(std::mktime(&date));
}