温馨提示×

CentOS下C++时间日期如何处理

小樊
37
2025-11-21 22:46:01
栏目: 编程语言

在 CentOS 系统下,C++ 可以使用 <ctime> 库来处理时间日期。以下是一些常用的时间日期处理方法:

  1. 获取当前时间:
#include <iostream>
#include <ctime>

int main() {
    std::time_t currentTime = std::time(nullptr);
    std::cout << "Current time: " << std::ctime(&currentTime) << std::endl;
    return 0;
}
  1. 将时间戳转换为可读的日期和时间:
#include <iostream>
#include <ctime>

int main() {
    std::time_t currentTime = std::time(nullptr);
    std::tm *localTime = std::localtime(&currentTime);

    char buffer[80];
    std::strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", localTime);
    std::cout << "Formatted time: " << buffer << std::endl;
    return 0;
}
  1. 解析字符串为时间戳:
#include <iostream>
#include <ctime>
#include <sstream>

std::tm parseDate(const std::string &dateStr) {
    std::tm tm = {};
    std::istringstream ss(dateStr);
    ss >> std::get_time(&tm, "%Y-%m-%d %H:%M:%S");
    return tm;
}

int main() {
    std::string dateStr = "2021-06-01 12:34:56";
    std::tm tm = parseDate(dateStr);

    std::time_t timeStamp = std::mktime(&tm);
    std::cout << "Timestamp: " << timeStamp << std::endl;
    return 0;
}
  1. 计算两个时间点之间的差值:
#include <iostream>
#include <ctime>

int main() {
    std::time_t time1 = std::time(nullptr);
    std::this_thread::sleep_for(std::chrono::seconds(2));
    std::time_t time2 = std::time(nullptr);

    double diffInSeconds = std::difftime(time2, time1);
    std::cout << "Difference in seconds: " << diffInSeconds << std::endl;
    return 0;
}

这些示例展示了如何在 CentOS 下使用 C++ 处理时间日期。你可以根据自己的需求进行修改和扩展。

0