在 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 進行轉換。