溫馨提示×

c++ datetime有哪些格式化技巧

c++
小樊
132
2024-07-12 15:18:36
欄目: 編程語言

在C++中處理日期和時間的庫有很多,比如<ctime>、<chrono>等。下面列舉一些常見的日期時間格式化技巧:

  1. 使用<ctime>庫中的strftime()函數可以將時間轉換成指定格式的字符串,例如:
#include <iostream>
#include <ctime>

int main() {
    time_t now = time(nullptr);
    char buffer[80];
    strftime(buffer, 80, "%Y-%m-%d %H:%M:%S", localtime(&now));
    std::cout << buffer << std::endl;
    return 0;
}
  1. 使用<chrono>庫中的system_clock、time_point等類可以更方便地處理時間,例如:
#include <iostream>
#include <chrono>

int main() {
    auto now = std::chrono::system_clock::now();
    std::time_t now_c = std::chrono::system_clock::to_time_t(now);
    std::cout << std::put_time(std::localtime(&now_c), "%Y-%m-%d %H:%M:%S") << std::endl;
    return 0;
}
  1. 使用第三方庫如Boost庫中的date_time可以更加靈活地處理日期和時間,例如:
#include <iostream>
#include <boost/date_time/gregorian/gregorian.hpp>

int main() {
    boost::gregorian::date today = boost::gregorian::day_clock::local_day();
    std::cout << today.year() << "-" << today.month() << "-" << today.day() << std::endl;
    return 0;
}

以上是一些常見的C++中處理日期和時間的格式化技巧,根據具體的需求選擇合適的庫和方法來進行處理。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女