时间转换 unix time stamp(时间戳), windows file time

 

 

#include <chrono>
#include <iostream>

#include <ctime>

using namespace std;

#pragma warning(disable:4996)

void unixTime2Str(__int64 n, char strTime[], int bufLen)
{
    struct tm loc_tm;
    errno_t  err = localtime_s(&loc_tm, &n);
    //errno_t  err = _localtime64_s(&tm, &n);
    if (err!= 0)
    {
        perror(strerror(err));
        return;
    }
    //std::cerr
    strftime(strTime, bufLen - 1, "%Y-%m-%d %H:%M:%S", &loc_tm);
    strTime[bufLen - 1] = '\0';
}


std::time_t getTimeStamp()
{
    std::chrono::time_point<std::chrono::system_clock, std::chrono::milliseconds> tp 
                = std::chrono::time_point_cast<std::chrono::milliseconds>(std::chrono::system_clock::now());

    auto tmp = std::chrono::duration_cast<std::chrono::milliseconds>(tp.time_since_epoch());
    std::time_t timestamp = tmp.count();
    //std::time_t timestamp = std::chrono::system_clock::to_time_t(tp);
    return timestamp;
}


std::tm* gettm(std::time_t timestamp)
{
    std::time_t milli = timestamp + (std::time_t)8 * 60 * 60 * 1000;//此处转化为东八区北京时间,如果是其它时区需要按需求修改
    auto mTime = std::chrono::milliseconds(milli);
    auto tp = std::chrono::time_point<std::chrono::system_clock, std::chrono::milliseconds>(mTime);
    auto tt = std::chrono::system_clock::to_time_t(tp);
    std::tm* now = std::gmtime(&tt);
    
    char strTime[100] = { 0 };
    strftime(strTime, sizeof(strTime) - 1, "%Y-%m-%d %H:%M:%S", now);
    printf(strTime);
    
    printf(" %4d年%02d月%02d日 %02d:%02d:%02d\n", now->tm_year + 1900, now->tm_mon + 1, now->tm_mday, now->tm_hour, now->tm_min, now->tm_sec);
    return now;
}


int main(int argc, char* argv[])
{
    char strTime[100] = { 0 };
    __int64 now = _time64(0);
    //__int64 now = 1444401700;
    //__int64 now = 1594813915910;
    //__int64 now = 1594997085523;
    unixTime2Str(now, strTime, sizeof(strTime));
    cout << getTimeStamp() << " ";
    gettm(getTimeStamp());
    cout << 1594813915910 << " ";
    gettm(1594813915910);

    cout << _time32(0) << " " << now << " " << strTime << endl;

    getchar();
    return 0 ;
}

  

posted @ 2020-07-17 23:13  乘于时  阅读(673)  评论(0编辑  收藏  举报