Reputation:
I read that I can show the current day, month and year with std::chrono
but how I can do that?
// 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?
Upvotes: 4
Views: 2105
Reputation: 4668
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)
Upvotes: 2
Reputation: 40070
std::put_time
is what you need:
#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
Upvotes: 8