用C++获取系统当前时间,然后格式化输出
时间: 2023-02-02 12:41:35 浏览: 93
C语言获取系统当前时间并格式化输出的代码如下:
```
#include <stdio.h>
#include <time.h>
int main()
{
time_t rawtime;
struct tm *timeinfo;
char buffer[80];
time(&rawtime);
timeinfo = localtime(&rawtime);
strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", timeinfo);
printf("当前时间: %s\n", buffer);
return 0;
}
```
这段代码使用了`time`和`localtime`函数从系统获取当前时间,再使用`strftime`函数格式化输出。
相关问题
使用c++写个使用boost库中函数 获取当前时间
可以使用Boost库中的posix_time模块来获取当前时间。下面是一个使用Boost库获取当前时间的示例代码:
```c++
#include <boost/date_time/posix_time/posix_time.hpp>
#include <iostream>
int main()
{
// 获取当前时间
boost::posix_time::ptime now = boost::posix_time::microsec_clock::local_time();
// 格式化输出时间
std::string str_time = boost::posix_time::to_simple_string(now);
std::cout << "Current time: " << str_time << std::endl;
return 0;
}
```
输出的结果类似于:
```
Current time: 2021-Aug-13 22:59:59.999999
```
可以看到,获取当前时间需要使用`boost::posix_time::microsec_clock::local_time()`函数,该函数返回的是一个`boost::posix_time::ptime`类型的时间戳。然后,可以使用`boost::posix_time::to_simple_string()`函数将时间戳格式化为字符串。
C++获取当前时间的年月日时分秒
C++获取当前时间的年月日时分秒可以使用time.h头文件中的函数和结构体来实现。具体方法可以参考以下代码:
```
#include <iostream>
#include <string>
#include <time.h>
struct NowDate {
char tmp0[16]; //年月日
char tmp1[16]; //时分秒
char tmp2[32]; //年月日时分秒
};
NowDate getTime() {
time_t timep;
time(&timep);
NowDate date;
strftime(date.tmp0, sizeof(date.tmp0), "%Y_%m_%d", localtime(&timep));
strftime(date.tmp1, sizeof(date.tmp1), "%H_%M_%S", localtime(&timep));
strftime(date.tmp2, sizeof(date.tmp2), "%Y%m%d%H%M%S", localtime(&timep));
return date;
}
int main() {
NowDate current_time = getTime();
std::string year_mom_day = current_time.tmp0;
std::string hour_mim_sec = current_time.tmp1;
std::string year_mom_day_hour_mim_sec = current_time.tmp2;
std::cout << year_mom_day << std::endl;
std::cout << hour_mim_sec << std::endl;
std::cout << year_mom_day_hour_mim_sec << std::endl;
system("pause");
}
```
其中,NowDate结构体中的三个成员变量分别存储年月日、时分秒和年月日时分秒。getTime()函数使用time()函数获取当前时间,然后使用strftime()函数将时间格式化为需要的字符串格式。最后,将格式化后的字符串存储到NowDate结构体中并返回。在main()函数中,调用getTime()函数获取当前时间并将其存储到字符串变量中,然后输出这些字符串即可。