問題描述
我一直在升級一些舊代碼,并在可能的情況下嘗試更新到 c++11.下面的代碼是我用來在我的程序中顯示時間和日期的方式
I have been upgrading some old code and have been trying to update to c++11 where possible. The following code is how I used to display the time and date in my program
#include <iostream>
#include <string>
#include <stdio.h>
#include <time.h>
const std::string return_current_time_and_date() const
{
time_t now = time(0);
struct tm tstruct;
char buf[80];
tstruct = *localtime(&now);
strftime(buf, sizeof(buf), "%Y-%m-%d %X", &tstruct);
return buf;
}
我想使用 std::chrono(或類似格式)以類似格式輸出當前時間和日期,但我不確定如何去做.任何幫助將不勝感激.謝謝
I would like to output the current time and date in a similar format using std::chrono(or similar) but am unsure how to go about doing so. Any help would be greatly appreciated. Thanks
推薦答案
庫只處理時間而不處理日期,除了 system_clock
能夠將其時間點轉換為 time_t
.因此,使用
表示日期不會有太大改善.希望我們能得到類似 chrono::date
的東西太遙遠的未來.
The <chrono>
library only deals with time and not dates, except for the system_clock
which has the ability to convert its timepoints to time_t
. So using <chrono>
for dates will not improve things much. Hopefully we get something like chrono::date
in the not too distant future.
也就是說,您可以通過以下方式使用
:
That said, you can use <chrono>
in the following way:
#include <chrono> // chrono::system_clock
#include <ctime> // localtime
#include <sstream> // stringstream
#include <iomanip> // put_time
#include <string> // string
std::string return_current_time_and_date()
{
auto now = std::chrono::system_clock::now();
auto in_time_t = std::chrono::system_clock::to_time_t(now);
std::stringstream ss;
ss << std::put_time(std::localtime(&in_time_t), "%Y-%m-%d %X");
return ss.str();
}
請注意,std::localtime
可能會導致數據競爭.localtime_r
或類似功能可能在您的平臺上可用.
Note that std::localtime
may cause data races. localtime_r
or similar functions may be available on your platforms.
更新:
使用 Howard Hinnant 的 日期庫 的新版本,您可以編寫:
Using a new version of Howard Hinnant's date library you can write:
#include "date.h"
#include <chrono>
#include <string>
#include <sstream>
std::string return_current_time_and_date() {
auto now = std::chrono::system_clock::now();
auto today = date::floor<days>(now);
std::stringstream ss;
ss << today << ' ' << date::make_time(now - today) << " UTC";
return ss.str();
}
這將打印出類似2015-07-24 05:15:34.043473124 UTC"的內容.
This will print out something like "2015-07-24 05:15:34.043473124 UTC".
在一個不相關的注釋中,返回 const
對象在 C++11 中變得不可?。徊荒芤苿?const 返回值.我還刪除了尾隨 const,因為尾隨 const 僅對成員函數有效,而該函數無需成為成員.
On an unrelated note, returning const
objects has become undesirable with C++11; const return values cannot be moved from. I also removed the trailing const because trailing const is only valid for member functions and this function has no need to be a member.
這篇關于使用 std::chrono 在 C++ 中輸出日期和時間的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!