c++时间戳格式化

使用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;
}


原文链接: https://www.cnblogs.com/52ld/p/17129412.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    c++时间戳格式化

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/318692

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月24日 下午3:00
下一篇 2023年2月24日 下午3:00

相关推荐