c++时间戳获取和转换

1、使用api

可以使用windows下和linux下api函数来获取,比较简单,如下所示:

int64_t getTimeStamp()
{
//毫秒数
    int mSecond = 0; 
#if defined(WIN32)
    SYSTEMTIME sys;
    GetLocalTime(&sys);
    mSecond = sys.wMilliseconds;
#else
//linux 下gettimeofday
    struct timeval    tv;
    struct timezone tz;
    struct tm* p;
    gettimeofday(&tv, &tz);
    p = localtime(&tv.tv_sec);
    mSecond = tv.tv_usec / 1000;
#endif
    int64_t timeStamp = ((int64_t)time(NULL)) * 1000 + mSecond;
    return timeStamp;
}

2、使用标准c++函数

使用标准c++就没有那么多麻烦了

  std::chrono::time_point<std::chrono::system_clock, std::chrono::milliseconds> tpMicro
        = std::chrono::time_point_cast<std::chrono::milliseconds>(std::chrono::system_clock::now());
    time_t timeStamp2 = tpMicro.time_since_epoch().count();

3、时间转time_t

对于一些不标准的字符串时间,我们需要转换时,可以十一用sscanf函数,windows下使用sscanf_s

time_t StringToDatetime(const char* str)
{
    tm tm_;
    int year, month, day, hour, minute, second;
    sscanf_s(str, "%d/%d/%d %d:%d:%d", &day, &month, &year, &hour, &minute, &second);
    tm_.tm_year = year - 1900;
    tm_.tm_mon = month - 1;
    tm_.tm_mday = day;
    tm_.tm_hour = hour;
    tm_.tm_min = minute;
    tm_.tm_sec = second;
    tm_.tm_isdst = 0;

    time_t t_ = mktime(&tm_); //已经减了8个时区  
    return t_; //秒时间  
}

4 、调用

int main()
{
    int64_t timeStamp = getTimeStamp();


    std::chrono::time_point<std::chrono::system_clock, std::chrono::milliseconds> tpMicro
        = std::chrono::time_point_cast<std::chrono::milliseconds>(std::chrono::system_clock::now());
    time_t timeStamp2 = tpMicro.time_since_epoch().count();


    std::cout << timeStamp << std::endl;
    std::cout << timeStamp2 << std::endl;
   
    std::string a = "1/4/2022 00:00:20";
    std::string b = "1/4/2022 00:00:01";
    time_t t1 = StringToDatetime(a.c_str());
    time_t t2 = StringToDatetime(b.c_str());

    std::cout << t2-t1<<"\n";
}

结果如下所示
c++时间戳获取和转换_第1张图片
可以看出c调用api函数和调用标准c++的结果是一样的。

你可能感兴趣的:(c++高级技巧,c++,c++,开发语言,时间戳)