global_time.h 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. #ifndef GLOBAL_TIME_H
  2. #define GLOBAL_TIME_H
  3. #include <time.h>
  4. #include <sys/time.h>
  5. // 定义全局时间结构体,包含所有需要的时间信息
  6. typedef struct {
  7. int wYear; // 年份(如:2023)
  8. int wMonth; // 月份(1-12)
  9. int wDay; // 日期(1-31)
  10. int wHour; // 小时(0-23)
  11. int wMinute; // 分钟(0-59)
  12. int wSecond; // 秒(0-59)
  13. int wMilliseconds; // 毫秒(0-999)
  14. } GlobalTime;
  15. inline int GetLocalTime(GlobalTime* pTime) {
  16. struct timeval tv;
  17. struct tm local_tm;
  18. GlobalTime g_stCurrentTime;
  19. if (pTime == NULL) {
  20. return -1;
  21. }
  22. // 获取当前时间(包含微秒)
  23. if (gettimeofday(&tv, NULL) != 0) {
  24. return -1;
  25. }
  26. // 转换为本地时间(线程安全版本)
  27. if (localtime_r(&tv.tv_sec, &local_tm) == NULL) {
  28. return -1;
  29. }
  30. // 填充全局时间结构体
  31. g_stCurrentTime.wYear = local_tm.tm_year + 1900; // 年份转换
  32. g_stCurrentTime.wMonth = local_tm.tm_mon + 1; // 月份转换(0-11 -> 1-12)
  33. g_stCurrentTime.wDay = local_tm.tm_mday;
  34. g_stCurrentTime.wHour = local_tm.tm_hour;
  35. g_stCurrentTime.wMinute = local_tm.tm_min;
  36. g_stCurrentTime.wSecond = local_tm.tm_sec;
  37. g_stCurrentTime.wMilliseconds = tv.tv_usec / 1000; // 微秒转毫秒
  38. *pTime = g_stCurrentTime;
  39. return 0;
  40. }
  41. #endif // GLOBAL_TIME_H