【发布时间】:2019-04-25 19:40:50
【问题描述】:
我需要在 C++ 中获取时间戳。我在chrono 中找到了一些函数,例如:
std::chrono::system_clock::now()
但它正在返回当前时间。如何获取一天的时间戳?我的意思是代表今天 00:00:00 和昨天相同的时间?我对 C++ 很陌生..
【问题讨论】:
-
那么,你为什么要标记c?
我需要在 C++ 中获取时间戳。我在chrono 中找到了一些函数,例如:
std::chrono::system_clock::now()
但它正在返回当前时间。如何获取一天的时间戳?我的意思是代表今天 00:00:00 和昨天相同的时间?我对 C++ 很陌生..
【问题讨论】:
我想,你只需要日期,没有时间。所以,你可以这样得到它:
#include <chrono>
#include <ctime>
#include <iomanip>
#include <iostream>
using namespace std;
int main()
{
auto curr = std::chrono::system_clock::now();
auto tm = std::chrono::system_clock::to_time_t(curr);
cout << std::put_time(std::localtime(&tm), "%d.%m.%Y");
}
当然,如果需要,您可以强制重置时间字段:
auto curr = std::chrono::system_clock::now();
time_t tm = std::chrono::system_clock::to_time_t(curr);
auto lt = std::localtime(&tm);
lt->tm_hour = 0;
lt->tm_min = 0;
lt->tm_sec = 0;
cout << lt->tm_mday << "." << lt->tm_mon + 1 << "." << lt->tm_year + 1900 << endl;
【讨论】: