2018年11月18日 星期日

C++ 學習筆記:chrono - Timepoint 與 C Calendar Time (ctime) 轉換

Example:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <chrono>
#include <ctime>
#include <string>
#include <iostream>

std::string asString(const std::chrono::system_clock::time_point& tp)
{
    constexpr bool blUseLocalTime = true;
    std::time_t t = std::chrono::system_clock::to_time_t(tp);
    std::string ts = blUseLocalTime ? std::ctime(&t) : std::asctime(gmtime(&t));
    ts.resize(ts.size() - 1);

    return ts; 
}

std::chrono::system_clock::time_point makeTimePoint (int year, int mon, int day,
                                                     int hour, int min, int sec = 0)
{
    struct std::tm t;
    t.tm_sec = sec;        // second of minute (0 .. 59 and 60 for leap seconds)
    t.tm_min = min;        // minute of hour (0 .. 59)
    t.tm_hour = hour;      // hour of day (0 .. 23)
    t.tm_mday = day;       // day of month (1 .. 31)
    t.tm_mon = mon - 1;    // month of year (0 .. 11)
    t.tm_year = year - 1900; // year since 1900
    t.tm_isdst = -1;       // determine whether daylight saving time

    auto tt = std::mktime(&t);
    if (tt == -1) {
        throw "no valid system time";
    }

    return std::chrono::system_clock::from_time_t(tt);
}

int main()
{
    auto tp1 = makeTimePoint(2010, 01, 01, 00, 00);
    std::cout << asString(tp1) << std::endl;

    auto tp2 = makeTimePoint(2011, 05, 23, 13, 44);
    std::cout << asString(tp2) << std::endl;
}

Note:
mktime 會考慮 local time zone, 沒有明確的方法可以指定 UTC time

Reference:
  1. The C++ Standard Library: A Tutorial and Reference, Second Edition

沒有留言:

張貼留言