[英]Show day, month and year with std::chrono?
I read that I can show the current day, month and year with std::chrono
but how I can do that? 我读到我可以用
std::chrono
显示当前的日,月和年但我怎么能这样做?
// Example program
#include <iostream>
#include <string>
#include <chrono>
int main()
{
using namespace std::chrono;
cout << std::chrono::day;
}
I do this code but it doesn't work, I always receive this 我做这个代码,但它不起作用,我总是收到这个
error: 'day' is not a member of 'std::chrono
What I'm doing wrong? 我做错了什么?
std::put_time
is what you need: 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";
}
Prints: 打印:
2018-05-14
2018年5月14日
A different approach based on std:strftime : 基于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
2018-05-14 19:33:11
( localtime_s
is outside of std namespace and uses a slightly different interface) (
localtime_s
在std命名空间之外并使用稍微不同的接口)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.