Linux c++ 打印系统时间,格式年月日 小时 分钟 秒 毫秒
时间: 2024-04-30 16:24:25 浏览: 11
你可以使用timeval结构体和gettimeofday函数来获取当前时间,并使用strftime函数将其格式化为年月日小时分钟秒毫秒的格式。下面是一个示例代码:
```c++
#include <iostream>
#include <sys/time.h>
#include <ctime>
int main()
{
timeval curTime;
gettimeofday(&curTime, NULL);
int milli = curTime.tv_usec / 1000;
char buffer[80];
strftime(buffer, 80, "%Y-%m-%d %H:%M:%S", localtime(&curTime.tv_sec));
char currentTime[84] = {0};
sprintf(currentTime, "%s:%d", buffer, milli);
std::cout << currentTime << std::endl;
return 0;
}
```
输出结果类似于:
```
2022-07-12 16:37:12:512
```
相关问题
用c++的代码获得当前时间的年月日分钟秒
可以使用C++标准库中的`<chrono>`和`<ctime>`头文件来获取当前时间的年月日分钟秒。以下是一个示例代码:
```c++
#include <chrono>
#include <ctime>
#include <iostream>
int main() {
// 获取当前时间
auto now = std::chrono::system_clock::now();
std::time_t time = std::chrono::system_clock::to_time_t(now);
// 转换为本地时间
struct std::tm* tm = std::localtime(&time);
// 获取年月日分钟秒
int year = tm->tm_year + 1900; // 年份需要加上 1900
int month = tm->tm_mon + 1; // 月份需要加上 1
int day = tm->tm_mday;
int hour = tm->tm_hour;
int minute = tm->tm_min;
int second = tm->tm_sec;
// 输出结果
std::cout << "Current time: " << year << "-" << month << "-" << day << " " << hour << ":" << minute << ":" << second << std::endl;
return 0;
}
```
输出结果类似于:`Current time: 2021-07-01 15:46:23`。
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()函数获取当前时间并将其存储到字符串变量中,然后输出这些字符串即可。