Is there a cross-platform way to get the current date and time in C++?
New answer for an old question:
The question does not specify in what timezone. There are two reasonable possibilities:
For 1, you can use this date library and the following program:
#include "date.h"
#include
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.
If you prefer 2 (the local time), there is a timezone library that builds on top of the date library. Both of these libraries are open source and cross platform, assuming the compiler supports C++11 or C++14.
#include "tz.h"
#include
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.
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.
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:
auto local = make_zoned("Australia/Sydney", system_clock::now());
And the output changes to:
2015-08-19 08:08:18.944211 AEST
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
.
As I write this, partial implementations are just beginning to emerge on some platforms.