GetCurrentTime

发布于:2025-03-16 ⋅ 阅读:(10) ⋅ 点赞:(0)

在实际编程中难免要获取当前时间并且进行格式化,本文给出了多种 GetCurrentTime() 方法以供选择。

C语言下使用strftime

C 语言中可以使用 <time.h> 中的函数来获取和格式化时间

#include <stdio.h>
#include <time.h>

char* getCurrentTime() {
    static char buffer[100];
    time_t now_time = time(NULL);
    struct tm* local_time = localtime(&now_time);
    strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", local_time);
    return buffer;
}

int main() {
    printf("Current Time: %s\n", getCurrentTime());
    return 0;
}

优点
• 简单直接,兼容性好。
• 无需额外依赖。

缺点
• 需要手动管理缓冲区。

C++11 方法

C++11 引入了 <chrono><iomanip>,提供了更现代化的时间处理方式。

#include <iostream>
#include <iomanip>
#include <sstream>
#include <chrono>
#include <ctime>

std::string getCurrentTime() {
    auto now = std::chrono::system_clock::now();
    std::time_t now_time = std::chrono::system_clock::to_time_t(now);
    std::tm local_time = *std::localtime(&now_time);

    std::ostringstream oss;
    oss << std::put_time(&local_time, "%Y-%m-%d %H:%M:%S");
    return oss.str();
}

int main() {
    std::cout << "Current Time: " << getCurrentTime() << std::endl;
    return 0;
}

优点
• 类型安全,无需手动管理缓冲区。
• 使用标准库函数,代码更简洁。

缺点
• 代码稍显冗长。

c++20

C++20 引入了 std::formatstd::chrono::format,提供了更简洁的格式化方式。

#include <iostream>
#include <chrono>
#include <format>

std::string getCurrentTime() {
    auto now = std::chrono::system_clock::now();
    return std::format("{:%Y-%m-%d %H:%M:%S}", now);
}

int main() {
    std::cout << "Current Time: " << getCurrentTime() << std::endl;
    return 0;
}

优点
• 代码简洁,现代化。
• 支持多种格式化方式。

缺点
• 需要 C++20 支持。

使用第三方库fmt

fmt 是一个功能强大的格式化库,支持 C++11 及以上版本。

#include <iostream>
#include <chrono>
#include <fmt/core.h>
#include <fmt/chrono.h>

std::string getCurrentTime() {
    auto now = std::chrono::system_clock::now();
    return fmt::format("{:%Y-%m-%d %H:%M:%S}", now);
}

int main() {
    std::cout << "Current Time: " << getCurrentTime() << std::endl;
    return 0;
}

优点
• 功能强大,支持 C++11 及以上版本。
• 代码简洁,类似于 C++20 的 std::format

缺点
• 需要引入第三方库。

使用 Boost 库

Boost 是一个功能丰富的 C++ 库,提供了时间处理工具。

#include <iostream>
#include <boost/date_time/posix_time/posix_time.hpp>

std::string getCurrentTime() {
    boost::posix_time::ptime now = boost::posix_time::second_clock::local_time();
    return boost::posix_time::to_simple_string(now);
}

int main() {
    std::cout << "Current Time: " << getCurrentTime() << std::endl;
    return 0;
}

优点
• 功能强大,支持多种时间操作。

缺点
• 需要引入 Boost 库。

**

方法 优点 缺点
C 语言 strftime 简单直接,兼容性好 需要手动管理缓冲区
C++11 std::put_time 类型安全,无需额外依赖 代码稍显冗长
C++20 std::format 简洁、现代化,支持多种格式化方式 需要 C++20 支持
fmt 功能强大,支持 C++11 及以上版本,类似 C++20 需要引入第三方库
Boost 库 功能丰富,支持多种时间操作 需要引入 Boost 库

根据你的项目需求和编译器支持情况,选择最适合的方案。如果可以使用 C++20,std::format 是最佳选择;否则,std::put_timefmt 库都是很好的替代方案。


网站公告

今日签到

点亮在社区的每一天
去签到