c++判断两个时间是否在一周

#include 
#include 

bool isSameWeek(std::time_t timestamp1, std::time_t timestamp2) {
    std::tm* timeinfo1 = std::localtime(×tamp1);
    std::tm* timeinfo2 = std::localtime(×tamp2);

    // 获取星期几
    int dayOfWeek1 = timeinfo1->tm_wday;
    int dayOfWeek2 = timeinfo2->tm_wday;

    // 获取当前日期是本周的第几天
    int daysToMonday1 = (dayOfWeek1 + 6) % 7;
    int daysToMonday2 = (dayOfWeek2 + 6) % 7;

    // 获取当前日期的起始时间(凌晨00:00:00)
    std::time_t startOfWeek1 = timestamp1 - daysToMonday1 * 24 * 60 * 60;
    std::time_t startOfWeek2 = timestamp2 - daysToMonday2 * 24 * 60 * 60;

    // 判断两个时间是否在同一周
    return (startOfWeek1 == startOfWeek2);
}

int main() {
    // 假设你有一个 int64_t 类型的时间戳
    int64_t yourTimestamp = 1641667200;  // 2022-01-09 12:00:00 UTC

    // 将 int64_t 转换为 std::time_t
    std::time_t yourTime = static_cast(yourTimestamp);

    // 获取当前时间
    std::time_t currentTime = std::time(NULL);

    if (isSameWeek(currentTime, yourTime)) {
        std::cout << "两个时间在同一周" << std::endl;
    } else {
        std::cout << "两个时间不在同一周" << std::endl;
    }

    return 0;
}

你可能感兴趣的:(c++,算法,开发语言)