簡體   English   中英

如何用time_t更改日期和時間的格式?

[英]How to change the format of date and time with time_t?

time_t now = time(0);  
std::string h = std::string (ctime (&now));

std::cout << "\nh: " << h;

我收到的當前輸出是: Thu Sep 14 10:58:26 2017

我希望輸出為2017-08-26-16-10-56

我該怎么做才能輸出?

使用strftime ,如下所示:

strftime (buffer, 80,"%Y-%m-%d-%H-%M-%S",timeinfo);

完整代碼:

#include <cstdio>
#include <ctime>

int main ()
{
  time_t rawtime;
  struct tm * timeinfo;
  char buffer [80];

  time (&rawtime);
  timeinfo = localtime (&rawtime);

  strftime (buffer, 80,"%Y-%m-%d-%H-%M-%S",timeinfo);
  puts (buffer);

  return 0;
}

輸出:

2017-09-14-14-41-19

使用std::put_time

#include <iomanip>

time_t now = time(0);
std::string h = std::put_time(localtime(&now), "%F-%H-%M-%S");
std::cout << "\nh: " << h;

產量

h:2017-09-14-05-54-02

更好的是,使用std::chrono

#include <iostream>
#include <iomanip>
#include <chrono>
using namespace std;

int main() {
    auto now = chrono::system_clock::to_time_t(chrono::system_clock::now());
    cout << put_time(localtime(&now), "%F-%H-%M-%S") << endl;
    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM