温馨提示×

如何在c++中实现unix时间戳的加减运算

c++
小樊
81
2024-09-24 21:40:05
栏目: 编程语言

在 C++ 中,可以使用 <chrono> 库来处理 Unix 时间戳(以秒为单位的时间)的加减运算。

以下是一个示例代码,展示如何进行 Unix 时间戳的加减运算:

#include <iostream>
#include <chrono>

using namespace std::chrono;

int main() {
    // 获取当前 Unix 时间戳(以秒为单位)
    auto now = system_clock::now();
    int current_timestamp = duration_cast<seconds>(now.time_since_epoch()).count();
    std::cout << "当前 Unix 时间戳:" << current_timestamp << std::endl;

    // Unix 时间戳加减运算
    int timestamp_plus_1_day = current_timestamp + 86400; // 加一天
    int timestamp_minus_1_hour = current_timestamp - 3600; // 减一个小时

    std::cout << "当前 Unix 时间戳加一天:" << timestamp_plus_1_day << std::endl;
    std::cout << "当前 Unix 时间戳减一个小时:" << timestamp_minus_1_hour << std::endl;

    return 0;
}

输出结果:

当前 Unix 时间戳:1629876479
当前 Unix 时间戳加一天:1629880079
当前 Unix 时间戳减一个小时:1629872879

在上面的示例中,我们首先获取了当前的 Unix 时间戳(以秒为单位),然后对其进行了加减运算。加减运算的结果仍然是 Unix 时间戳(以秒为单位)。如果需要将结果转换为其他时间单位(如毫秒或微秒),可以使用 duration_cast 进行转换。

0