#include <stdio.h>
#include <string.h>
#include <time.h>

/**
 * @brief 比较两个时间字符串的大小
 *
 * @param time1 时间字符串1，格式为 "HH:MM"
 * @param time2 时间字符串2，格式为 "HH:MM"
 *
 * @return 返回值为整数：
 *         -1 表示 time1 小于 time2
 *          0 表示 time1 等于 time2
 *          1 表示 time1 大于 time2
 *          0 也可能表示解析失败或转换失败
 *
 * @details 该函数将两个时间字符串解析为 struct tm 结构，并使用 mktime 函数将其转换为 time_t 类型，
 *          然后比较这两个时间，返回相应的比较结果。如果解析或转换失败，函数返回 0。
 */
int compareTimes(const char *time1, const char *time2) {
    struct tm tm_base, tm_time1, tm_time2;

    // 设置基准日期为当前日期
    time_t current_time = time(NULL);
    localtime_r(&current_time, &tm_base);

    // 解析时间字符串1
    if (strptime(time1, "%H:%M", &tm_time1) == NULL) {
        fprintf(stderr, "Failed to parse time1\n");
        return 0; // or handle the error in an appropriate way
    }

    // 解析时间字符串2
    if (strptime(time2, "%H:%M", &tm_time2) == NULL) {
        fprintf(stderr, "Failed to parse time2\n");
        return 0; // or handle the error in an appropriate way
    }

    // 设置日期部分为基准日期的日期部分
    tm_time1.tm_year = tm_base.tm_year;
    tm_time1.tm_mon = tm_base.tm_mon;
    tm_time1.tm_mday = tm_base.tm_mday;

    tm_time2.tm_year = tm_base.tm_year;
    tm_time2.tm_mon = tm_base.tm_mon;
    tm_time2.tm_mday = tm_base.tm_mday;

    // 将 struct tm 结构转换为 time_t 类型
    time_t t1 = mktime(&tm_time1);
    time_t t2 = mktime(&tm_time2);

    // 检查转换是否成功
    if (t1 == -1 || t2 == -1) {
        fprintf(stderr, "Failed to convert time to time_t\n");
        return 0; // or handle the error in an appropriate way
    }

    // 比较时间并返回相应的结果
    if (t1 < t2) {
        return -1;
    } else if (t1 > t2) {
        return 1;
    } else {
        return 0;
    }
}

int main() {
    const char *time1 = "2025-12-7 12:11:01";
    const char *time2 = "15:45";

    int result = compareTimes(time1, time2);

    if (result < 0) {
        printf("%s is earlier than %s\n", time1, time2);
    } else if (result > 0) {
        printf("%s is later than %s\n", time1, time2);
    } else {
        printf("%s is equal to %s\n", time1, time2);
    }

    return 0;
}