【问题标题】:Show day, month and year with std::chrono?用 std::chrono 显示日、月和年?
【发布时间】:2018-05-14 17:08:02
【问题描述】:

我读到我可以用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

我做错了什么?

【问题讨论】:

标签: c++ chrono


【解决方案1】:

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-05-14

【讨论】:

  • 在 Visual Studio 2017 上,我不推荐使用 localtime,它让我可以改用 localtime_s,这需要 2 个参数。使用 localtime_s put_time 不起作用。 ):
  • @TuğberkKaanDuman 我同情你。 std::localtime 不推荐使用,由标准定义。 (再次)对 MSVC 感到羞耻。
  • 我得到的确切错误是:Function 'localtime' is deprecated, reason: 'This function or variable may be unsafe. Consider using localtime_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details. 为什么微软遵循不同的标准? D:
  • @TuğberkKaanDuman 因为它是 Microsoft - 他们有自己的 _s 版本的许多 C 样式 API 函数,如 memcpy、strcpy 等。
  • @hauron 但他们为什么要重新发明轮子?这些功能真的不安全吗?
【解决方案2】:

基于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;
}

结果:

2018-05-14 19:33:11

localtime_s 位于 std 命名空间之外,使用的接口略有不同)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多