How to get current time and date in C++?

1,413,316

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:

  1. In UTC.
  2. 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;
}
Share:
1,413,316
Hanut
Author by

Hanut

Updated on July 08, 2022

Comments

  • Hanut
    Hanut almost 2 years

    Is there a cross-platform way to get the current date and time in C++?

  • Oleg Vazhnev
    Oleg Vazhnev almost 11 years
    in VS2012 i have to add #define _CRT_SECURE_NO_DEPRECATE before include to make program compiles
  • DevSolar
    DevSolar over 10 years
    This 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
    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
    historystamp over 10 years
    Didn't compile for me. Being a novice I cannot comment on why.
  • Léa Massiot
    Léa Massiot almost 10 years
    Hello. 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
    barranquero almost 10 years
    The return type is "const std::string", so it is returned by value and then a copy of buffer is made, before releasing it.
  • bduhbya
    bduhbya over 9 years
    Sure: 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
    feelfree over 9 years
    This will not work as TIMESTAMP will give the time when the file is created rather than the current time.
  • derpface
    derpface over 9 years
    The question asks for cross-platform. Windows.h is Windows-specific, and void main isn't even standard C/C++.
  • Maxwell175
    Maxwell175 about 9 years
    anon's answer below has a better structure and provides a better example.
  • Johannes
    Johannes almost 9 years
    This should be upvoted because it's the most portable and easy way in current C++.
  • Martin Broadhurst
    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
    Steed over 7 years
    This 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
    Frederick The Fool over 7 years
    Examples exist at the linked page.
  • Lightness Races in Orbit
    Lightness Races in Orbit over 7 years
    Why return const value? That's purposeless.
  • Fernando Gonzalez Sanchez
    Fernando Gonzalez Sanchez over 7 years
    This 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
    Alston about 7 years
    how to change the result of std::chrono::system_clock::now() to string? not cout
  • STF
    STF about 7 years
    Why did you ask if the ptmNow->tm_day < 9 and not <10?
  • Joe
    Joe about 7 years
    I 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
    STF about 7 years
    So you need to ask if it's <=9 because you want to include also 9.
  • Joe
    Joe about 7 years
    Note I have a 1+ in the code. Day/Month starts at 0.
  • STF
    STF about 7 years
    month start at 0, but day start at 1!
  • Joe
    Joe about 7 years
    Yes you are correct. Then just change <9 to <=9 or <10, and remove the +1 at day.
  • v010dya
    v010dya about 7 years
    This is the worst answer possible. It makes other c++11 answers a duplicate, and yet it explains nothing, being a 'link only'.
  • jterm
    jterm almost 7 years
    Also, he asked about C++ not C.
  • Joseph Farah
    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
    Tarc almost 7 years
    There'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 from stream, or how to properly format a time_point<>, go ahead and ask another question or google after it.
  • Ziagl
    Ziagl about 6 years
    plus 1 for cross-platform solution!
  • Jonathan Mee
    Jonathan Mee almost 6 years
    Shouldn't localtime give me the time in my timezone?
  • Howard Hinnant
    Howard Hinnant almost 6 years
    Yes, 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
    James Robert Albert over 5 years
    looking back at this, I have no idea why I felt equipped to answer a C++ question
  • selfboot
    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
    JasonArg123 about 4 years
    I 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
    ThermoX over 3 years
    Why 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
    Alex M over 2 years
    C4996 '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
    Frederick The Fool over 2 years
    @ThermoX Welcome to C++
  • 463035818_is_not_a_number
    463035818_is_not_a_number over 2 years
    would be cool if you could also provide the update for UTC. Because the obvious std::cout << std::chrono::system_clock::now(); fails
  • Howard Hinnant
    Howard Hinnant over 2 years
    The obvious should work. Perhaps it hasn't been implemented by your std::lib vendor yet? eel.is/c++draft/…
  • 425nesp
    425nesp almost 2 years
    This 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
    q0987 almost 2 years
    I tried this with gnu++20 and here is the error: "error: ‘zoned_time’ was not declared in this scope"
  • Howard Hinnant
    Howard Hinnant almost 2 years
    Here is the status of gcc implementing C++20 library features: gcc.gnu.org/onlinedocs/libstdc++/manual/…