如何在 C++ 中获取当前时间和日期?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/997946/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get current time and date in C++?
提问by Max Frai
Is there a cross-platform way to get the current date and time in C++?
是否有跨平台的方式来获取 C++ 中的当前日期和时间?
回答by Frederick The Fool
In C++ 11 you can use std::chrono::system_clock::now()
在 C++ 11 中,您可以使用 std::chrono::system_clock::now()
Example (copied from en.cppreference.com):
示例(从en.cppreference.com复制):
#include <iostream>
#include <chrono>
#include <ctime>
int main()
{
auto start = std::chrono::system_clock::now();
// Some computation here
auto end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = end-start;
std::time_t end_time = std::chrono::system_clock::to_time_t(end);
std::cout << "finished computation at " << std::ctime(&end_time)
<< "elapsed time: " << elapsed_seconds.count() << "s\n";
}
This should print something like this:
这应该打印如下内容:
finished computation at Mon Oct 2 00:59:08 2017
elapsed time: 1.88232s
回答by Frederick The Fool
C++ shares its date/time functions with C. The tm structureis probably the easiest for a C++ programmer to work with - the following prints today's date:
C++ 与 C 共享它的日期/时间函数。tm 结构可能是 C++ 程序员最容易使用的 - 以下打印今天的日期:
#include <ctime>
#include <iostream>
int main() {
std::time_t t = std::time(0); // get time now
std::tm* now = std::localtime(&t);
std::cout << (now->tm_year + 1900) << '-'
<< (now->tm_mon + 1) << '-'
<< now->tm_mday
<< "\n";
}
回答by TrungTN
You can try the following cross-platform code to get current date/time:
您可以尝试以下跨平台代码来获取当前日期/时间:
#include <iostream>
#include <string>
#include <stdio.h>
#include <time.h>
// Get current date/time, format is YYYY-MM-DD.HH:mm:ss
const std::string currentDateTime() {
time_t now = time(0);
struct tm tstruct;
char buf[80];
tstruct = *localtime(&now);
// Visit http://en.cppreference.com/w/cpp/chrono/c/strftime
// for more information about date/time format
strftime(buf, sizeof(buf), "%Y-%m-%d.%X", &tstruct);
return buf;
}
int main() {
std::cout << "currentDateTime()=" << currentDateTime() << std::endl;
getchar(); // wait for keyboard input
}
Output:
输出:
currentDateTime()=2012-05-06.21:47:59
Please visit herefor more information about date/time format
请访问此处了解有关日期/时间格式的更多信息
回答by Martin York
std C libraries provide time()
.
This is seconds from the epoch and can be converted to date and H:M:S
using standard C functions. Boostalso has a time/date librarythat you can check.
std C 库提供time()
. 这是从纪元开始的几秒钟,可以转换为日期并H:M:S
使用标准 C 函数。Boost还有一个时间/日期库,您可以查看。
time_t timev;
time(&timev);
回答by Vaibhav Patle
the C++ standard library does not provide a proper date type. C++ inherits the structs and functions for date and time manipulation from C, along with a couple of date/time input and output functions that take into account localization.
C++ 标准库没有提供正确的日期类型。C++ 从 C 继承了用于日期和时间操作的结构和函数,以及一些考虑到本地化的日期/时间输入和输出函数。
// Current date/time based on current system
time_t now = time(0);
// Convert now to tm struct for local timezone
tm* localtm = localtime(&now);
cout << "The local date and time is: " << asctime(localtm) << endl;
// Convert now to tm struct for UTC
tm* gmtm = gmtime(&now);
if (gmtm != NULL) {
cout << "The UTC date and time is: " << asctime(gmtm) << endl;
}
else {
cerr << "Failed to get the UTC date and time" << endl;
return EXIT_FAILURE;
}
回答by Howard Hinnant
New answer for an old question:
旧问题的新答案:
The question does not specify in what timezone. There are two reasonable possibilities:
问题没有指定在哪个时区。有两种合理的可能性:
- In UTC.
- In the computer's local timezone.
- 在 UTC。
- 在计算机的本地时区。
For 1, you can use this date libraryand the following program:
对于 1,您可以使用此日期库和以下程序:
#include "date.h"
#include <iostream>
int
main()
{
using namespace date;
using namespace std::chrono;
std::cout << system_clock::now() << '\n';
}
Which just output for me:
这只是为我输出:
2015-08-18 22:08:18.944211
The date library essentially just adds a streaming operator for std::chrono::system_clock::time_point
. It also adds a lot of other nice functionality, but that is not used in this simple program.
日期库本质上只是为std::chrono::system_clock::time_point
. 它还添加了许多其他不错的功能,但是在这个简单的程序中没有使用这些功能。
If you prefer 2 (the local time), there is a timezone librarythat builds on top of the date library. Both of these libraries are open sourceand cross platform, assuming the compiler supports C++11 or C++14.
如果您更喜欢 2(本地时间),则有一个建立在日期库之上的时区库。这两个库都是开源和跨平台的,假设编译器支持 C++11 或 C++14。
#include "tz.h"
#include <iostream>
int
main()
{
using namespace date;
using namespace std::chrono;
auto local = make_zoned(current_zone(), system_clock::now());
std::cout << local << '\n';
}
Which for me just output:
这对我来说只是输出:
2015-08-18 18:08:18.944211 EDT
The result type from make_zoned
is a date::zoned_time
which is a pairing of a date::time_zone
and a std::chrono::system_clock::time_point
. This pair represents a local time, but can also represent UTC, depending on how you query it.
结果类型 frommake_zoned
是 a date::zoned_time
,它是 adate::time_zone
和 a的配对std::chrono::system_clock::time_point
。这对表示本地时间,但也可以表示 UTC,具体取决于您查询它的方式。
With the above output, you can see that my computer is currently in a timezone with a UTC offset of -4h, and an abbreviation of EDT.
通过上面的输出,您可以看到我的计算机当前处于 UTC 偏移量为 -4h 且缩写为 EDT 的时区。
If some other timezone is desired, that can also be accomplished. For example to find the current time in Sydney , Australia just change the construction of the variable local
to:
如果需要其他时区,也可以实现。例如,要查找澳大利亚悉尼的当前时间,只需将变量的构造更改local
为:
auto local = make_zoned("Australia/Sydney", system_clock::now());
And the output changes to:
并且输出更改为:
2015-08-19 08:08:18.944211 AEST
Update for C++20
C++20 更新
This library is now largely adopted for C++20. The namespace date
is gone and everything is in namespace std::chrono
now. And use zoned_time
in place of make_time
. Drop the headers "date.h"
and "tz.h"
and just use <chrono>
.
该库现在主要用于 C++20。命名空间date
消失了,std::chrono
现在一切都在命名空间中。并zoned_time
代替make_time
. 删除标题"date.h"
,"tz.h"
然后使用<chrono>
.
As I write this, partial implementations are just beginning to emerge on some platforms.
在我撰写本文时,部分实现才刚刚开始在某些平台上出现。
回答by Offirmo
(For fellow googlers)
(对于谷歌同事)
There is also Boost::date_time:
#include <boost/date_time/posix_time/posix_time.hpp>
boost::posix_time::ptime date_time = boost::posix_time::microsec_clock::universal_time();
回答by Roi Danton
auto time = std::time(nullptr);
std::cout << std::put_time(std::localtime(&time), "%F %T%z"); // ISO 8601 format.
Get the current time either using std::time()
or std::chrono::system_clock::now()
(or another clock type).
使用std::time()
或std::chrono::system_clock::now()
(或其他时钟类型)获取当前时间。
std::put_time()
(C++11) and strftime()
(C) offer a lot of formatters to output those times.
std::put_time()
(C++11) 和strftime()
(C) 提供了很多格式化程序来输出这些时间。
#include <iomanip>
#include <iostream>
int main() {
auto time = std::time(nullptr);
std::cout
// ISO 8601: %Y-%m-%d %H:%M:%S, e.g. 2017-07-31 00:42:00+0200.
<< std::put_time(std::gmtime(&time), "%F %T%z") << '\n'
// %m/%d/%y, e.g. 07/31/17
<< std::put_time(std::gmtime(&time), "%D");
}
The sequence of the formatters matters:
格式化程序的顺序很重要:
std::cout << std::put_time(std::gmtime(&time), "%c %A %Z") << std::endl;
// Mon Jul 31 00:00:42 2017 Monday GMT
std::cout << std::put_time(std::gmtime(&time), "%Z %c %A") << std::endl;
// GMT Mon Jul 31 00:00:42 2017 Monday
The formatters of strftime()
are similar:
的格式化程序strftime()
类似:
char output[100];
if (std::strftime(output, sizeof(output), "%F", std::gmtime(&time))) {
std::cout << output << '\n'; // %Y-%m-%d, e.g. 2017-07-31
}
Often, the capital formatter means "full version" and lowercase means abbreviation (e.g. Y: 2017, y: 17).
通常,大写格式表示“完整版”,小写表示缩写(例如 Y: 2017, y: 17)。
Locale settings alter the output:
区域设置改变输出:
#include <iomanip>
#include <iostream>
int main() {
auto time = std::time(nullptr);
std::cout << "undef: " << std::put_time(std::gmtime(&time), "%c") << '\n';
std::cout.imbue(std::locale("en_US.utf8"));
std::cout << "en_US: " << std::put_time(std::gmtime(&time), "%c") << '\n';
std::cout.imbue(std::locale("en_GB.utf8"));
std::cout << "en_GB: " << std::put_time(std::gmtime(&time), "%c") << '\n';
std::cout.imbue(std::locale("de_DE.utf8"));
std::cout << "de_DE: " << std::put_time(std::gmtime(&time), "%c") << '\n';
std::cout.imbue(std::locale("ja_JP.utf8"));
std::cout << "ja_JP: " << std::put_time(std::gmtime(&time), "%c") << '\n';
std::cout.imbue(std::locale("ru_RU.utf8"));
std::cout << "ru_RU: " << std::put_time(std::gmtime(&time), "%c");
}
Possible output (Coliru, Compiler Explorer):
可能的输出(Coliru,Compiler Explorer):
undef: Tue Aug 1 08:29:30 2017
en_US: Tue 01 Aug 2017 08:29:30 AM GMT
en_GB: Tue 01 Aug 2017 08:29:30 GMT
de_DE: Di 01 Aug 2017 08:29:30 GMT
ja_JP: 2017年08月01日 08時29分30秒
ru_RU: Вт 01 авг 2017 08:29:30
I've used std::gmtime()
for conversion to UTC. std::localtime()
is provided to convert to local time.
我已经用于std::gmtime()
转换为 UTC。std::localtime()
提供转换为本地时间。
Heed that asctime()
/ctime()
which were mentioned in other answers are marked as deprecated now and strftime()
should be preferred.
回答by etcheve
#include <stdio.h>
#include <time.h>
int main ()
{
time_t rawtime;
struct tm * timeinfo;
time ( &rawtime );
timeinfo = localtime ( &rawtime );
printf ( "Current local time and date: %s", asctime (timeinfo) );
return 0;
}
回答by 0x499602D2
Yes and you can do so with formatting rules specified by the currently-imbued locale:
是的,您可以使用当前流行的语言环境指定的格式规则来执行此操作:
#include <iostream>
#include <iterator>
#include <string>
class timefmt
{
public:
timefmt(std::string fmt)
: format(fmt) { }
friend std::ostream& operator <<(std::ostream &, timefmt const &);
private:
std::string format;
};
std::ostream& operator <<(std::ostream& os, timefmt const& mt)
{
std::ostream::sentry s(os);
if (s)
{
std::time_t t = std::time(0);
std::tm const* tm = std::localtime(&t);
std::ostreambuf_iterator<char> out(os);
std::use_facet<std::time_put<char>>(os.getloc())
.put(out, os, os.fill(),
tm, &mt.format[0], &mt.format[0] + mt.format.size());
}
os.width(0);
return os;
}
int main()
{
std::cout << timefmt("%c");
}
Output:
Fri Sep 6 20:33:31 2013
输出:
Fri Sep 6 20:33:31 2013