C++ 時間字符串的格式化輸出


第一種方法,包含毫秒字段

std::string GetDate(std::chrono::system_clock::time_point time_point)
{
    auto seconds = std::chrono::duration_cast<std::chrono::seconds>(
        time_point.time_since_epoch());

    auto milliseconds = std::chrono::duration_cast<std::chrono::milliseconds>(
                            time_point.time_since_epoch()) -
                        seconds;

    auto sec = static_cast<time_t>(seconds.count());
    std::tm tm;
    ::gmtime_r(&sec, &tm);

    char buff[32] = {0};
    auto size = std::strftime(buff, sizeof(buff), "%Y-%m-%d %H:%M:%S", &tm);
    return std::string(buff, size) + "." + std::to_string(milliseconds.count());
}

2.使用put_time格式化字符串

static std::string FormatTimePoint(const std::chrono::system_clock::time_point &time_point,
                                   const std::string &format = "%Y-%m-%d %X")
{
  auto in_time_t = std::chrono::system_clock::to_time_t(time_point);
  std::stringstream ss;
  ss << std::put_time(std::localtime(&in_time_t), format.c_str());
  return ss.str();
}

使用方法如下:

int main()
{
  // 方法一
  std::cout << GetDate() << std::endl;
  // 方法二
  const std::chrono::time_point<std::chrono::system_clock> now =
      std::chrono::system_clock::now();
  std::cout << FormatTimePoint(now) << std::endl;
  return 0;
}

結果輸出:

2022-03-25 12:17:57.336
2022-03-25 12:17:57

Process finished with exit code 0


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM