How to get current time and date in C++?
Solution 1
In C++ 11 you can use std::chrono::system_clock::now()
Example (copied from 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" <<
<< std::endl;
}
This should print something like this:
finished computation at Mon Oct 2 00:59:08 2017
elapsed time: 1.88232s
Solution 2
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 here for more information about date/time format
Solution 3
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. Boost also has a time/date library that you can check.
time_t timev;
time(&timev);
Solution 4
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.
For 1, you can use this date library and the following program:
#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.
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 <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.
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
Update for 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>
.
#include <chrono>
#include <iostream>
int
main()
{
using namespace std::chrono;
auto local = zoned_time{current_zone(), system_clock::now()};
std::cout << local << '\n'; // 2021-05-03 15:02:44.130182 EDT
}
As I write this, partial implementations are just beginning to emerge on some platforms.
Solution 5
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.
// 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;
}
Hanut
Updated on July 08, 2022Comments
-
Hanut almost 2 years
Is there a cross-platform way to get the current date and time in C++?
-
Oleg Vazhnev almost 11 yearsin VS2012 i have to add
#define _CRT_SECURE_NO_DEPRECATE
before include to make program compiles -
DevSolar over 10 yearsThis is, IMHO, actually the best answer, since it is the only one that honors locale settings, and because it is programmed with such attention to detail (you don't see
ostream::sentry
that often). -
David G over 10 years@DevSolar Thanks. I wouldn't say it's the best though. I've seen better implementations. But I think this suffices for an example :)
-
historystamp over 10 yearsDidn't compile for me. Being a novice I cannot comment on why.
-
Léa Massiot almost 10 yearsHello. I have a little problem with this "buf" allocation inside the function "currentDateTime()". How is it supposed to persist after the function has returned? Thx.
-
barranquero almost 10 yearsThe return type is "const std::string", so it is returned by value and then a copy of buffer is made, before releasing it.
-
bduhbya over 9 yearsSure:
time_t rawTime; time(&rawTime); struct tm *timeInfo; char buf[80]; timeInfo = localtime(&rawTime); strftime(buf, 80, "%T", timeInfo);
This particular one just puts the HH:MM:SS. My first post so I m not sure how to get the code format correct. Sorry about that. -
feelfree over 9 yearsThis will not work as TIMESTAMP will give the time when the file is created rather than the current time.
-
derpface over 9 yearsThe question asks for cross-platform. Windows.h is Windows-specific, and
void main
isn't even standard C/C++. -
Maxwell175 about 9 yearsanon's answer below has a better structure and provides a better example.
-
Johannes almost 9 yearsThis should be upvoted because it's the most portable and easy way in current C++.
-
Martin Broadhurst about 8 years@Johannes, just added mine. At this rate, this should be the top answer by 15 August 2017, 16:31 UTC :-)
-
Steed over 7 yearsThis answer is of very little use without examples of using the obtained value. E.g. how can you print it, get local time, compare with other date/time?
-
Frederick The Fool over 7 yearsExamples exist at the linked page.
-
Lightness Races in Orbit over 7 yearsWhy return
const
value? That's purposeless. -
Fernando Gonzalez Sanchez over 7 yearsThis is a good example, but the line 'strftime(buf, sizeof(buf), "%H:%M:%S %P", &tstruct);' must have the %P converted to %p (the latest one is standard, the upper case one causes an assertion in MSVC 2015).
-
Alston about 7 yearshow to change the result of
std::chrono::system_clock::now()
to string? notcout
-
STF about 7 yearsWhy did you ask if the
ptmNow->tm_day < 9
and not<10
? -
Joe about 7 yearsI want a day (say day X) less than 9 to be 0X (i.e. 1 -> 01, 9 -> 09) to fill up the space, in order to match our design. Day 10 can simply be 10 in the string.
-
STF about 7 yearsSo you need to ask if it's
<=9
because you want to include also 9. -
Joe about 7 yearsNote I have a
1+
in the code. Day/Month starts at 0. -
STF about 7 yearsmonth start at 0, but day start at 1!
-
Joe about 7 yearsYes you are correct. Then just change <9 to <=9 or <10, and remove the +1 at day.
-
v010dya about 7 yearsThis is the worst answer possible. It makes other c++11 answers a duplicate, and yet it explains nothing, being a 'link only'.
-
jterm almost 7 yearsAlso, he asked about C++ not C.
-
Joseph Farah almost 7 years@jterm its ok, C and C++ share the exact same time library, its a matter of different import names and thats it
-
Tarc almost 7 yearsThere's no way to get more to the point than this answer. The OP was asking "Is there a cross-platform way to get the current date and time in C++?" This question gives you exactly this. If you are in doubt about how to get a
string
fromstream
, or how to properly format atime_point<>
, go ahead and ask another question or google after it. -
Ziagl about 6 yearsplus 1 for cross-platform solution!
-
Jonathan Mee almost 6 yearsShouldn't
localtime
give me the time in my timezone? -
Howard Hinnant almost 6 yearsYes,
localtime
will nearly always give you the time in your local timezone to second precision. Sometimes it will fail because of threadsafety issues, and it will never work for subsecond precision. -
James Robert Albert over 5 yearslooking back at this, I have no idea why I felt equipped to answer a C++ question
-
selfboot almost 5 years
__TIMESTAMP__
is a preprocessor macro that expands to current time (at compile time) in the form Ddd Mmm Date hh::mm::ss yyyy. The__TIMESTAMP__
macro can be used to provide information about the particular moment a binary was built. Refer: cprogramming.com/reference/preprocessor/__TIMESTAMP__.html -
JasonArg123 about 4 yearsI tried using ctime(&end_time) like this and get the following compile error: error C4996: 'ctime': This function or variable may be unsafe. Consider using ctime_s instead. Is it standard practice to use ctime_s for compiling on Windows?
-
ThermoX over 3 yearsWhy isn't there some simple function I can call, which would capture the current local time, with member functions giving me access to all components found in struct tm and some other string conversion functions. All these calls to get basic, common information and add 1900 here, 1 there. Seems absurd.
-
Alex M over 2 yearsC4996 'ctime': This function or variable may be unsafe. Consider using ctime_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.
-
Frederick The Fool over 2 years@ThermoX Welcome to C++
-
463035818_is_not_a_number over 2 yearswould be cool if you could also provide the update for UTC. Because the obvious
std::cout << std::chrono::system_clock::now();
fails -
Howard Hinnant over 2 yearsThe obvious should work. Perhaps it hasn't been implemented by your std::lib vendor yet? eel.is/c++draft/…
-
425nesp almost 2 yearsThis doesn't get you the current time... it gets a duration between two times... How do you just print what the current time is?
-
q0987 almost 2 yearsI tried this with gnu++20 and here is the error: "error: ‘zoned_time’ was not declared in this scope"
-
Howard Hinnant almost 2 yearsHere is the status of gcc implementing C++20 library features: gcc.gnu.org/onlinedocs/libstdc++/manual/…