C/C++11的毫秒时间戳和日期互转

180it 2020-10-10 AM 3782℃ 0条
// 需要开启c++11支持,g++ test.cpp -std=c++11 -o test
// 这里默认是东八区北京时间格式
#include <iostream>
#include <chrono>
#include <cstdio>
using namespace std;

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(long long timestamp)
{
    auto milli = timestamp + (long long)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);
    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()
{
    system("chcp 65001");
    char time_str[4][16];
    auto t = getTimeStamp();
    std::cout << "Millisecond timestamp is: " << t << std::endl;
    auto time_ptr = gettm(t);
    sprintf(time_str[0], "%02d", time_ptr->tm_mon + 1); //月份要加1
    sprintf(time_str[1], "%02d", time_ptr->tm_mday);//天
    sprintf(time_str[2], "%02d", time_ptr->tm_hour);//时
    sprintf(time_str[3], "%02d", time_ptr->tm_min);// 分
    for(int i = 0; i < 4; i++)
    {
        std::cout << "time_str[" << i << "] is: " << time_str[i] << std::endl;
    }
}
支付宝打赏支付宝打赏 微信打赏微信打赏

如果文章或资源对您有帮助,欢迎打赏作者。一路走来,感谢有您!

标签: none

C/C++11的毫秒时间戳和日期互转