123456789101112131415161718192021222324252627282930313233343536373839404142434445464748 |
- #ifndef GLOBAL_TIME_H
- #define GLOBAL_TIME_H
- #include <time.h>
- #include <sys/time.h>
- // 定义全局时间结构体,包含所有需要的时间信息
- typedef struct {
- int wYear; // 年份(如:2023)
- int wMonth; // 月份(1-12)
- int wDay; // 日期(1-31)
- int wHour; // 小时(0-23)
- int wMinute; // 分钟(0-59)
- int wSecond; // 秒(0-59)
- int wMilliseconds; // 毫秒(0-999)
- } GlobalTime;
- inline int GetLocalTime(GlobalTime* pTime) {
- struct timeval tv;
- struct tm local_tm;
- GlobalTime g_stCurrentTime;
- if (pTime == NULL) {
- return -1;
- }
- // 获取当前时间(包含微秒)
- if (gettimeofday(&tv, NULL) != 0) {
- return -1;
- }
-
- // 转换为本地时间(线程安全版本)
- if (localtime_r(&tv.tv_sec, &local_tm) == NULL) {
- return -1;
- }
-
- // 填充全局时间结构体
- g_stCurrentTime.wYear = local_tm.tm_year + 1900; // 年份转换
- g_stCurrentTime.wMonth = local_tm.tm_mon + 1; // 月份转换(0-11 -> 1-12)
- g_stCurrentTime.wDay = local_tm.tm_mday;
- g_stCurrentTime.wHour = local_tm.tm_hour;
- g_stCurrentTime.wMinute = local_tm.tm_min;
- g_stCurrentTime.wSecond = local_tm.tm_sec;
- g_stCurrentTime.wMilliseconds = tv.tv_usec / 1000; // 微秒转毫秒
-
- *pTime = g_stCurrentTime;
- return 0;
- }
- #endif // GLOBAL_TIME_H
|