【问题标题】:C++ get current dateC++ 获取当前日期
【发布时间】:2016-06-18 19:17:46
【问题描述】:

我想获取当前时间日/月/年时:分:秒 当涉及到这样一个简单的问题时,C++ 似乎很恶心(嗯,它本身就是)。

我已经在互联网上搜索过,我所能得到的只是不推荐使用的 c 函数或线程不安全的函数。我找到了这样的方式:

std::time_t const now_c = std::time(0);
auto strTime = std::put_time(std::localtime(&now_c), "%F %T");

但是,我需要使用

#pragma warning(disable : 4996)

甚至能够编译它(Visual Studio 会说:error C4996: 'localtime': This function or variable may be unsafe. 请考虑改用 localtime_s。要禁用弃用,请使用 _CRT_SECURE_NO_WARNINGS。)

如何以优雅、有效、不弃用、高效、明智和 C++ 的方式获取当前日期?

【问题讨论】:

  • 我推荐看看这个优秀的c++11 onwards date library
  • 也许std::tm 可以帮助你?我知道你说 localtime 已被弃用,但它符合 c++11
  • localtime 不会以任何方式被弃用,只是被微软认为是“不安全的”。如果您不同意这一点,只需将 _CRT_SECURE_NO_WARNINGS 添加到您项目的宏中即可。
  • #define _CRT_SECURE_NO_WARNINGS 是明智的
  • 好的,没关系就用define。

标签: c++ date get


【解决方案1】:

std::localtime 没有被弃用,只是被微软编译器称为“不安全”,应用它来避免

#define _CRT_SECURE_NO_WARNINGS

【讨论】:

    【解决方案2】:

    如何以优雅、有效、不弃用、高效、明智和 C++ 的方式获取当前日期?

    以下是使用 cmets 中 ArchbishopOfBanterbury 提到的 free, open-source C++11/14 library 的方法:

    #include "tz.h"
    #include <string>
    
    int
    main()
    {
        auto const now = date::make_zoned(date::current_zone(),
                                          std::chrono::system_clock::now());
        auto strTime = date::format("%F %T", now);
    }
    

    这是线程安全的,并使用现代 C++11/14 &lt;chrono&gt; 库作为其基础。这将输出时间精确到system_clock::time_point(VS 为 100ns)。如果您希望将其截断为秒,则可以这样完成:

    using namespace std::chrono;
    using namespace date;
    auto const now = make_zoned(current_zone(), floor<seconds>(system_clock::now()));
    auto strTime = format("%F %T", now);
    

    如果您想获取其他地方的当地时间,只需输入该时区的IANA name 代替current_zone()

    auto const now = make_zoned("Europe/London", floor<seconds>(system_clock::now()));
    

    【讨论】:

      猜你喜欢
      • 2011-10-18
      • 2017-02-27
      • 2020-01-09
      • 1970-01-01
      • 1970-01-01
      • 2023-02-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多