C++当前时间 ->两位数
C++ current time -> two digits
我通过
显示当前日期/时间#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个问题:
- 我想要两位数,即日期(日和月)以及时间(小时,分钟和第二个)。因此,它应该显示04.10.2016和09:54:00
- 今天,它显示了2016年10月24日,但今天是24.11.2016。为什么显示十月而不是十一月?linux-clock正确显示时间。
感谢您的所有帮助:)
-
您应该使用操纵器进行打印。在printf中("%02d",curtime-> tm_hour)在Cout中,您可以使用,std :: cout&lt;&lt;std :: setW(2)&lt;&lt;std :: setFill('0')&lt;&lt;curtime-> tm_hour。
-
tm_mon从0到11。因此,您应该使用tm_mon 1进行打印。
对于您的格式,请尝试std :: strftime
- 有几种方法。
如果您使用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;
- 如User7777777所述,tm_mon = 0..11。
相关文章:
- 在两个线程上读/写 64 位,无互斥/锁定/原子
- 从两个 4x64 位整数数组中获取取模
- 如何在C ++中替换整数的前两位数字?
- 如何输出计算到小数点后两位的中间器?
- 将两位数字转换为低内存表示的最快方法
- 如何在计算器中将大数字表示为小数点后两位C++
- 可视化 如何使用C++向右强制小数点后两位
- 四舍五入双小数点后两位
- 将浮点数限制为小数点后两位
- C++ 如何获取兰登数以及如何保存带有 ONY 两位小数的双精度
- 使用 "double" 输出具有两位小数的值
- 程序查找并打印第一个完全正方形 (i*i),其最后两位数字都是奇数
- 转换为十六进制并删除最后两位数字
- 我将如何在不使用 if 语句、字符数组、apstring 或 atoi 的情况下将带有两位数字的字符串转换为 int
- C++四舍五入小数点后两位
- 如何正确格式化c++浮点数到小数点后两位
- 四舍五入浮点数:精确地输出小数点后的两位数字
- 我在试着编写一种疾病在不同年龄段的发病率,我需要把它写成一个百分数它的精度是小数点后两位
- 如何将双精度转换为小数点后两位
- 将字节转换为两位十六进制数字