我读到我可以用std::chrono
显示当前的日期,月份和年份,但我该怎么做?
// Example program
#include <iostream>
#include <string>
#include <chrono>
int main()
{
using namespace std::chrono;
cout << std::chrono::day;
}
我执行此代码但它不起作用,我总是收到此
error: 'day' is not a member of 'std::chrono
我做错了什么?
答案 0 :(得分:9)
std::put_time
就是您所需要的:
#include <chrono>
#include <iostream>
#include <iomanip>
#include <ctime>
int main()
{
auto now = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
std::cout << std::put_time(std::localtime(&now), "%Y-%m-%d") << "\n";
}
打印:
2018年5月14日
答案 1 :(得分:2)
A different approach based on std:strftime:
#include <iomanip>
#include <ctime>
#include <chrono>
#include <iostream>
int main()
{
auto now_c = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
std::tm ptm;
localtime_s(&ptm, &now_c);
char buffer[80];
std::strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S ", &ptm);
std::cout << buffer;
}
Result:
2018-05-14 19:33:11
(localtime_s
is outside of std namespace and uses a slightly different interface)