温馨提示×

CentOS C++时间函数如何使用

小樊
53
2025-07-14 17:59:04
栏目: 编程语言

在 CentOS 系统中,C++ 可以使用 <ctime> 库来处理时间相关的功能。下面是一些常用的时间函数及其用法示例:

  1. 获取当前时间

    使用 std::time 函数可以获取当前的日历时间。

    #include <iostream>
    #include <ctime>
    
    int main() {
        std::time_t currentTime = std::time(nullptr);
        std::cout << "Current time: " << std::ctime(&currentTime);
        return 0;
    }
    

    std::ctime 返回一个表示时间的字符串。

  2. 将时间转换为本地时间

    使用 std::localtime 函数可以将 std::time_t 类型的时间转换为本地时间。

    #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 << "Local time: " << buffer << std::endl;
        return 0;
    }
    
  3. 获取特定时间点的值

    可以使用 std::tm 结构来设置特定的日期和时间,然后使用 std::mktime 转换为 std::time_t

    #include <iostream>
    #include <ctime>
    
    int main() {
        std::tm timeStruct = {};
        timeStruct.tm_year = 2023 - 1900; // 年份从1900开始
        timeStruct.tm_mon = 10 - 1;      // 月份从0开始
        timeStruct.tm_mday = 1;          // 日
        timeStruct.tm_hour = 12;         // 小时
        timeStruct.tm_min = 30;          // 分钟
        timeStruct.tm_sec = 45;          // 秒
    
        std::time_t specificTime = std::mktime(&timeStruct);
        std::cout << "Specific time: " << std::ctime(&specificTime);
        return 0;
    }
    
  4. 睡眠函数

    如果需要让程序暂停一段时间,可以使用 std::sleepstd::usleep

    #include <iostream>
    #include <thread>
    #include <chrono>
    
    int main() {
        std::cout << "Sleeping for 2 seconds..." << std::endl;
        std::this_thread::sleep_for(std::chrono::seconds(2));
        std::cout << "Awake now!" << std::endl;
        return 0;
    }
    

    注意:std::sleepstd::usleep 在 POSIX 系统上可用,如果在 Windows 上编译,可能需要使用不同的方法,例如 Sleep 函数。

这些是 C++ 中处理时间的一些基本用法。根据具体需求,还可以使用其他功能,如时间戳转换、格式化输出等。

0