【问题标题】:C++ current time -> two digitsC++ 当前时间 -> 两位数
【发布时间】:2023-04-07 13:33:02
【问题描述】:

我通过显示当前日期/时间

#include <ctime>
time_t sec = time(NULL);
tm* curTime = localtime(&sec);    
cout << "Date: " <<  curTime->tm_mday << "." << curTime->tm_mon << "." << curTime->tm_year+1900 << endl;
cout << "Time: " << curTime->tm_hour << ":" << curTime->tm_min << ":" << curTime->tm_sec << endl;

实际上它显示例如

Date: 4.10.2016
Time: 9:54:0

我在这里遇到了 2 个问题:

  1. 我想要两位数字,日期(日和月)和时间(小时、分钟和秒)。所以它应该显示 04.10.2016 和 09:54:00
  2. 今天显示的是 24.10.2016,但今天是 24.11.2016。为什么显示的是 10 月而不是 11 月? Linux 时钟正确显示时间。

感谢您的帮助:)

【问题讨论】:

  • 2.月份的索引从 0 到 11(0 是 1 月,11 是 12 月)所以你必须 +1 到数字
  • 您使用哪种 C++ 标准?
  • 我正在使用 -std=c++0x,因为 -std=c++11 在我的计算机上没有以某种方式激活(而且我无权更改它)。

标签: c++ date time digits ctime


【解决方案1】:
  1. 您应该使用操纵器进行打印。 在 printf("%02d", curTime->tm_hour) 在 cout 中,您可以使用, std::cout tm_hour.

  2. tm_mon 是从 0 到 11。所以你应该使用 tm_mon+1 来打印。

【讨论】:

  • 太棒了!谢谢...没想到 setfill(0) :)
【解决方案2】:

对于您的格式,请尝试std::strftime

【讨论】:

    【解决方案3】:
    1. 有几种方法。

    如果您使用 C++11 并且您的编译器已实现 iomanip 标头中的 std::put_time() (但不幸的是,这不是您的情况):

    std::cout << "Date: " << std::put_time(curTime, "%d.%m.%Y") << std::endl;
    std::cout << "Time: " << std::put_time(curTime, "%H:%M:%S") << std::endl;
    

    如果您使用较旧的编译器版本(您的情况):

    std::string to_string(const char* format, tm* time) {
        std::vector<char> buf(100, '\0');
        buf.resize(std::strftime(buf.data(), buf.size(), format, time));
        return std::string(buf.begin(), buf.end());
    }
    std::cout << "Date: " << to_string("%d.%m.%Y", curTime) << std::endl;
    std::cout << "Time: " << to_string("%H.%M.%S", curTime) << std::endl;
    
    1. 正如 user7777777 所述,tm_mon = 0..11。

    【讨论】:

      猜你喜欢
      • 2017-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-15
      • 1970-01-01
      • 1970-01-01
      • 2021-03-14
      • 2017-04-27
      相关资源
      最近更新 更多