chrono库及C和POSIX提供的Date/Time函数灵活运用

#include <iostream>
#include <chrono>
#include <string>
#include <exception>
using namespace std;
//将time_point转换为string
string asString(const chrono::system_clock::time_point& tp)
{
    time_t t = chrono::system_clock::to_time_t(tp);
    string ts = ctime(&t);
    //去掉newline字符
    ts.resize(ts.size() - 1);
    return ts;
}
//strcut tm 转换成time_point
chrono::time_point<chrono::system_clock> makeTimePoint(int year, int mon, int day, int hour, int min, int sec = 0)
{
    struct tm t;
    t.tm_year = year - 1900;
    t.tm_mon = mon - 1;
    t.tm_mday = day;
    t.tm_hour = hour;
    t.tm_min = min;
    t.tm_sec = sec;
    time_t tt = mktime(&t);
    if (tt == -1)
        throw "Invalid system time";
    return chrono::system_clock::from_time_t(tt);
}
//将time_point转换成struct tm
tm* makeTM(chrono::system_clock::time_point& tp)
{
    time_t t = chrono::system_clock::to_time_t(tp);
    return localtime(&t);//考虑时区
    // return gmtime(&t) //不考虑时区
}
//格式化输出时间
void echoTime(tm *t)
{
    char buffer[128];
    strftime(buffer, sizeof(buffer), "%F %T", t);
    cout << buffer;
}
int main()
{
    cout << asString(makeTimePoint(2017, 5, 01, 12, 00)) << endl;
    cout << asString(chrono::system_clock::from_time_t(mktime(makeTM(chrono::system_clock::now())))) << endl;
    echoTime(makeTM(chrono::system_clock::now()));
    system("pause");
    return 0;
}

你可能感兴趣的:(C++,chrono)