首页 > 编程语言 >c++时间戳格式化

c++时间戳格式化

时间:2023-02-17 11:12:35浏览次数:43  
标签:std 格式化 chrono c++ tm 时间 time date include

使用chrono获取当前系统时间,使用std::put_time 将时间标准化

时间戳格式化为指定的字符串
#include <chrono>
#include <iostream>
#include <iomanip>
#include <ctime>

void test_system_clock()
{
    using namespace std;
    auto t = chrono::system_clock::to_time_t(chrono::system_clock::now());
    cout << std::put_time(std::localtime(&t), "%Y-%m-%d %X") << endl;
    cout << std::put_time(std::localtime(&t), "%Y-%m-%d %H.%M.%S") << endl;
}

按照输入格式的字符串生成对应的时间戳
点击查看代码
#include <iostream>
#include <chrono>
#include <ctime>

int main() {
    std::string date_time_str = "2022-07-11_19:03:56.458";
    int year, month, day, hour, minute, second;
    sscanf_s(date_time_str.c_str(), "%d-%d-%d_%d:%d:%d", &year, &month, &day, &hour, &minute, &second);
    std::tm date_time = {};
    date_time.tm_year = year - 1900;
    date_time.tm_mon = month - 1;
    date_time.tm_mday = day;
    date_time.tm_hour = hour;
    date_time.tm_min = minute;
    date_time.tm_sec = second;
    auto timestamp = std::chrono::system_clock::from_time_t(std::mktime(&date_time));
    auto duration = timestamp.time_since_epoch();
    auto millis = std::chrono::duration_cast<std::chrono::milliseconds>(duration).count();
    std::cout << millis << "\n";
    return 0;
}


标签:std,格式化,chrono,c++,tm,时间,time,date,include
From: https://www.cnblogs.com/52ld/p/17129412.html

相关文章