C++当前时间 ->两位数

C++ current time -> two digits

本文关键字:两位 gt 时间 C++      更新时间:2023-10-16

我通过

显示当前日期/时间
#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. 今天,它显示了2016年10月24日,但今天是24.11.2016。为什么显示十月而不是十一月?linux-clock正确显示时间。

感谢您的所有帮助:)

  1. 您应该使用操纵器进行打印。在printf中("%02d",curtime-> tm_hour)在Cout中,您可以使用,std :: cout&lt;&lt;std :: setW(2)&lt;&lt;std :: setFill('0')&lt;&lt;curtime-> tm_hour。

  2. tm_mon从0到11。因此,您应该使用tm_mon 1进行打印。

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

  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, '');
    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。