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