time_test.txt 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <time.h>
  4. /**
  5. * @brief 比较两个时间字符串的大小
  6. *
  7. * @param time1 时间字符串1,格式为 "HH:MM"
  8. * @param time2 时间字符串2,格式为 "HH:MM"
  9. *
  10. * @return 返回值为整数:
  11. * -1 表示 time1 小于 time2
  12. * 0 表示 time1 等于 time2
  13. * 1 表示 time1 大于 time2
  14. * 0 也可能表示解析失败或转换失败
  15. *
  16. * @details 该函数将两个时间字符串解析为 struct tm 结构,并使用 mktime 函数将其转换为 time_t 类型,
  17. * 然后比较这两个时间,返回相应的比较结果。如果解析或转换失败,函数返回 0。
  18. */
  19. int compareTimes(const char *time1, const char *time2) {
  20. struct tm tm_base, tm_time1, tm_time2;
  21. // 设置基准日期为当前日期
  22. time_t current_time = time(NULL);
  23. localtime_r(&current_time, &tm_base);
  24. // 解析时间字符串1
  25. if (strptime(time1, "%H:%M", &tm_time1) == NULL) {
  26. fprintf(stderr, "Failed to parse time1\n");
  27. return 0; // or handle the error in an appropriate way
  28. }
  29. // 解析时间字符串2
  30. if (strptime(time2, "%H:%M", &tm_time2) == NULL) {
  31. fprintf(stderr, "Failed to parse time2\n");
  32. return 0; // or handle the error in an appropriate way
  33. }
  34. // 设置日期部分为基准日期的日期部分
  35. tm_time1.tm_year = tm_base.tm_year;
  36. tm_time1.tm_mon = tm_base.tm_mon;
  37. tm_time1.tm_mday = tm_base.tm_mday;
  38. tm_time2.tm_year = tm_base.tm_year;
  39. tm_time2.tm_mon = tm_base.tm_mon;
  40. tm_time2.tm_mday = tm_base.tm_mday;
  41. // 将 struct tm 结构转换为 time_t 类型
  42. time_t t1 = mktime(&tm_time1);
  43. time_t t2 = mktime(&tm_time2);
  44. // 检查转换是否成功
  45. if (t1 == -1 || t2 == -1) {
  46. fprintf(stderr, "Failed to convert time to time_t\n");
  47. return 0; // or handle the error in an appropriate way
  48. }
  49. // 比较时间并返回相应的结果
  50. if (t1 < t2) {
  51. return -1;
  52. } else if (t1 > t2) {
  53. return 1;
  54. } else {
  55. return 0;
  56. }
  57. }
  58. int main() {
  59. const char *time1 = "12:11";
  60. const char *time2 = "15:45";
  61. int result = compareTimes(time1, time2);
  62. if (result < 0) {
  63. printf("%s is earlier than %s\n", time1, time2);
  64. } else if (result > 0) {
  65. printf("%s is later than %s\n", time1, time2);
  66. } else {
  67. printf("%s is equal to %s\n", time1, time2);
  68. }
  69. return 0;
  70. }