简体   繁体   English

用std :: chrono显示日,月和年?

[英]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.

相关问题 如何获取 std::chrono::time_point<std::chrono::system_clock, std::chrono::seconds> 来自年、月、日、小时、分钟和秒的变量?</std::chrono::system_clock,> - How to get std::chrono::time_point<std::chrono::system_clock, std::chrono::seconds> from variables of year,month,day,hour,minute and seconds? 如何从 C++ 中的 std::chrono::year_month_day 获取星期几 - How to get the weekday number from std::chrono::year_month_day in C++ 从C ++中的std :: chrono :: time_point中提取年/月/日等 - Extract year/month/day etc. from std::chrono::time_point in C++ 如何将 chrono::year_month_day 添加到 chrono::sys_seconds - How to add chrono::year_month_day to chrono::sys_seconds 如何从年、月、日、小时、分钟、秒、毫秒中获取计时时间点? - How to get chrono time_point from year, month, day, hour, minute, second, millisecond? 使用boost :: chrono,如何从单独的年,月,日,时,分,秒分别计算自纪元UTC以来的毫秒数 - Using boost::chrono, how to calculate milliseconds since epoch UTC from separate year, month, day, hour,min,secs 如果 d &gt; 255,为什么 std::chrono::day 存储值未指定 - Why std::chrono::day stored value is unspecified if d > 255 无法设置wxDateTime日,月和年 - Cannot set wxDateTime day, month and year C++ 月、日、年验证 - C++ Month, day, and year validation C++ 将日、月、年转换为毫秒 - C++ convert day, month and year to milliseconds
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM