628

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

jackyalcine
  • 469
  • 1
  • 8
  • 21
Max Frai
  • 61,946
  • 78
  • 197
  • 306
  • 3
    If Ockonal is still active, he should change the accepted answer to the C++11 approach. This question still seems to get a lot of views. – JSQuareD Apr 09 '16 at 15:35
  • 2
    C version: http://stackoverflow.com/questions/1442116/how-to-get-date-and-time-value-in-c-program – Ciro Santilli OurBigBook.com Sep 18 '16 at 08:08
  • 3
    @JSQuareD Even looking at this question now after all this time, I find the C approach better using the `tm` structure. Doesn't the C++11 approach just give the unix timestamp (time since epoch) although the question was about getting the date and time? – Snackoverflow Jan 21 '18 at 00:13
  • 4
    Wow, this question has 1,110,886 views! People really love C++! – User123 Mar 10 '20 at 17:19
  • 4
    No, they just hate ::std::chrono. It's indecipherable gibberish. – Yttrill May 06 '21 at 23:03

26 Answers26

884

Since 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
flederwiesel
  • 447
  • 1
  • 9
  • 17
G S
  • 35,511
  • 22
  • 84
  • 118
  • 40
    This should be upvoted because it's the most portable and easy way in current C++. – Johannes May 09 '15 at 12:07
  • 5
    @Johannes, just added mine. At this rate, this should be the top answer by 15 August 2017, 16:31 UTC :-) –  Feb 26 '16 at 23:30
  • 71
    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? – Steed Aug 24 '16 at 10:16
  • 2
    Examples exist at the linked page. – G S Aug 30 '16 at 05:26
  • 5
    how to change the result of `std::chrono::system_clock::now()` to string? not `cout` – Alston Feb 09 '17 at 04:08
  • 40
    This is the worst answer possible. It makes other c++11 answers a duplicate, and yet it explains nothing, being a 'link only'. – v010dya Mar 14 '17 at 12:15
  • 11
    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. – Tarc Jul 07 '17 at 17:02
  • 1
    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? – JasonArg123 Feb 04 '20 at 17:48
  • 2
    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. – ThermoX Dec 19 '20 at 05:53
  • 2
    @ThermoX Welcome to C++ – G S Nov 03 '21 at 04:30
  • 1
    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? – 425nesp May 01 '22 at 01:15
  • @425nesp The first line - "finished computation at" - is the current time. now() gives the current time (as a time_point: https://en.cppreference.com/w/cpp/chrono/time_point) – Hapaxia May 27 '23 at 22:22
539

C++ shares its date/time functions with C. The tm structure is probably the easiest for a C++ programmer to work with - the following prints today's date:

#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";
}
milleniumbug
  • 15,379
  • 3
  • 47
  • 71
  • 28
    Use `ctime()` together with this answer if you want a date string. – rtn Jun 15 '09 at 19:42
  • 3
    what about deleting the instance of `struct tm` is it possible to just call delete on it? – Petr Aug 08 '14 at 13:59
  • 5
    @Petr you only need to call delete on memory allocated with new. – iheanyi Aug 15 '14 at 16:52
  • 5
    ok but still you get a pointer from localtime() so the structure instance gets allocated on heap or not? which means it doesn't get cleaned unless you do that somehow. I never said use `delete` (c++ keyword) on it, I just thought it should be deleted somehow :) or who is going to do that for you? – Petr Aug 23 '14 at 09:46
  • 9
    @Petr You don't need to deallocate it because it is allocated statically, see here for this topic http://stackoverflow.com/questions/8694365/how-is-the-result-struct-of-localtime-allocated-in-c – Brandin Aug 29 '14 at 21:09
  • Question: Is there a reason to have the variable 'now' be a pointer? Why not just say: struct tm now =* localtime( & t ); – DowntownDev Aug 20 '16 at 21:37
  • @Hard.Core.Coder: Why make an unnecessary copy? – Ed S. Apr 07 '17 at 22:11
  • why need to add 1900 for year and add 1 to month? – slier May 21 '17 at 14:50
  • 2
    @slier Because `tm_year` counts from 1900 and `tm_mon` has the range [0, 11] by definition. E.g. see the link in the answer. – Roi Danton Jul 31 '17 at 14:34
  • One more question - how to do the same for milliseconds? – Mikhail_Sam Aug 16 '17 at 07:13
  • `std::time_t t = std::time(0)` is not UTC nor locale... it is epoch (so totally universal). OK, you could say epoch is UTC0, well, yes. So why `std::gmtime(t)` produces wrong UTC time? Is is not really UTC? – Sandburg Jul 22 '19 at 12:46
  • Why do you have the `+ 1900`? (this is not a rhetorical question, I want to learn) – Cardinal System Dec 01 '20 at 21:11
  • Use `localtime_s` instead for thread-safe reason – guan boshen Nov 10 '21 at 11:02
  • As I can't Edit this answer (due to the stupid *"Suggested edit que is full"* reason), the output of the above program is *"today's date"* e.g. `2022-9-2`. It doesn't output time! – Milan Sep 02 '22 at 16:01
  • When I run this my timestamp looks like this: `apISt4pairI5UnitsS4_EdSt4lessIS5_ESaIS3_IKS5_dEEEEEE` – Raleigh L. Sep 30 '22 at 07:20
221

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

Rashad
  • 11,057
  • 4
  • 45
  • 73
TrungTN
  • 2,412
  • 1
  • 14
  • 4
142

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);
sashoalm
  • 75,001
  • 122
  • 434
  • 781
Martin York
  • 257,169
  • 86
  • 333
  • 562
48

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.

Howard Hinnant
  • 206,506
  • 52
  • 449
  • 577
  • Shouldn't `localtime` give me the time in my timezone? – Jonathan Mee Jun 18 '18 at 20:26
  • 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. – Howard Hinnant Jun 18 '18 at 21:14
  • 1
    would be cool if you could also provide the update for UTC. Because the obvious `std::cout << std::chrono::system_clock::now();` fails – 463035818_is_not_an_ai Nov 18 '21 at 14:41
  • The obvious should work. Perhaps it hasn't been implemented by your std::lib vendor yet? http://eel.is/c++draft/time.clock.system.nonmembers#lib:operator%3c%3c,sys_time – Howard Hinnant Nov 18 '21 at 16:46
  • I tried this with gnu++20 and here is the error: "error: ‘zoned_time’ was not declared in this scope" – q0987 May 29 '22 at 22:40
  • Here is the status of gcc implementing C++20 library features: https://gcc.gnu.org/onlinedocs/libstdc++/manual/status.html#status.iso.2020 – Howard Hinnant May 30 '22 at 02:30
31

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;
}
Vaibhav Patle
  • 571
  • 6
  • 5
25
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::put_time() (C++11) and strftime() (C) offer a lot of formatters to output those times.

#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:

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).


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):

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.

Heed that asctime()/ctime() which were mentioned in other answers are marked as deprecated now and strftime() should be preferred.

Roi Danton
  • 7,933
  • 6
  • 68
  • 80
  • `std::put_time()` doesn't work with the output of `std::chrono::system_clock::now()`. – remcycles Jul 28 '22 at 19:07
  • 1
    You can use [`std::chrono::system_clock::to_time_t()`](https://en.cppreference.com/w/cpp/chrono/system_clock/to_time_t) to convert the output of the system clock. – Roi Danton Aug 02 '22 at 08:54
21

(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();
Offirmo
  • 18,962
  • 12
  • 76
  • 97
14
#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;
} 
etcheve
  • 151
  • 1
  • 2
12

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

David G
  • 94,763
  • 41
  • 167
  • 253
  • 2
    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). – DevSolar Oct 11 '13 at 20:24
  • @DevSolar Thanks. I wouldn't say it's the best though. I've seen better implementations. But I think this suffices for an example :) – David G Oct 11 '13 at 20:31
  • Didn't compile for me. Being a novice I cannot comment on why. – historystamp Nov 13 '13 at 16:47
10

you could use C++ 11 time class:

    #include <iostream>
    #include <iomanip>
    using namespace std;

    int main() {

       time_t now = chrono::system_clock::to_time_t(chrono::system_clock::now());
       cout << put_time(localtime(&now), "%F %T") <<  endl;
      return 0;
     }

out put:

2017-08-25 12:30:08
Sam Abdul
  • 109
  • 1
  • 4
8

There's always the __TIMESTAMP__ preprocessor macro.

#include <iostream>

using namespace std

void printBuildDateTime () {
    cout << __TIMESTAMP__ << endl;
}

int main() {
    printBuildDateTime();
}

example: Sun Apr 13 11:28:08 2014

James Robert Albert
  • 404
  • 1
  • 5
  • 13
  • 30
    This will not work as __TIMESTAMP__ will give the time when the file is created rather than the current time. – feelfree Aug 11 '14 at 13:41
  • 5
    looking back at this, I have no idea why I felt equipped to answer a C++ question – James Robert Albert Nov 17 '18 at 03:42
  • 1
    `__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: https://www.cprogramming.com/reference/preprocessor/__TIMESTAMP__.html – selfboot May 17 '19 at 01:55
6

std::ctime

Why was ctime only mentioned in the comments so far?

#include <ctime>
#include <iostream>
 
int main()
{
    std::time_t result = std::time(nullptr);
    std::cout << std::ctime(&result);
}

Output

Tue Dec 27 17:21:29 2011

Markus Dutschke
  • 9,341
  • 4
  • 63
  • 58
  • 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. – Alex M Oct 24 '21 at 09:24
5

You can use the following code to get the current system date and time in C++ :

    #include <iostream>
    #include <time.h> //It may be #include <ctime> or any other header file depending upon
                     // compiler or IDE you're using 
    using namespace std;

    int main() {
       // current date/time based on current system
       time_t now = time(0);

       // convert now to string form
       string dt = ctime(&now);

       cout << "The local date and time is: " << dt << endl;
    return 0;
    }

PS: Visit this site for more information.

Deepanshu
  • 141
  • 1
  • 5
4

You can also directly use ctime():

#include <stdio.h>
#include <time.h>

int main ()
{
  time_t rawtime;
  struct tm * timeinfo;

  time ( &rawtime );
  printf ( "Current local time and date: %s", ctime (&rawtime) );

  return 0;
} 
Abhishek Gupta
  • 6,465
  • 10
  • 50
  • 82
4

I found this link pretty useful for my implementation: C++ Date and Time

Here's the code I use in my implementation, to get a clear "YYYYMMDD HHMMSS" output format. The param in is for switching between UTC and local time. You can easily modify my code to suite your need.

#include <iostream>
#include <ctime>

using namespace std;

/**
 * This function gets the current date time
 * @param useLocalTime true if want to use local time, default to false (UTC)
 * @return current datetime in the format of "YYYYMMDD HHMMSS"
 */

string getCurrentDateTime(bool useLocalTime) {
    stringstream currentDateTime;
    // current date/time based on current system
    time_t ttNow = time(0);
    tm * ptmNow;

    if (useLocalTime)
        ptmNow = localtime(&ttNow);
    else
        ptmNow = gmtime(&ttNow);

    currentDateTime << 1900 + ptmNow->tm_year;

    //month
    if (ptmNow->tm_mon < 9)
        //Fill in the leading 0 if less than 10
        currentDateTime << "0" << 1 + ptmNow->tm_mon;
    else
        currentDateTime << (1 + ptmNow->tm_mon);

    //day
    if (ptmNow->tm_mday < 10)
        currentDateTime << "0" << ptmNow->tm_mday << " ";
    else
        currentDateTime <<  ptmNow->tm_mday << " ";

    //hour
    if (ptmNow->tm_hour < 10)
        currentDateTime << "0" << ptmNow->tm_hour;
    else
        currentDateTime << ptmNow->tm_hour;

    //min
    if (ptmNow->tm_min < 10)
        currentDateTime << "0" << ptmNow->tm_min;
    else
        currentDateTime << ptmNow->tm_min;

    //sec
    if (ptmNow->tm_sec < 10)
        currentDateTime << "0" << ptmNow->tm_sec;
    else
        currentDateTime << ptmNow->tm_sec;


    return currentDateTime.str();
}

Output (UTC, EST):

20161123 000454
20161122 190454
Joe
  • 841
  • 2
  • 10
  • 25
3

This works with G++ I'm not sure if this helps you. Program output:

The current time is 11:43:41 am
The current date is 6-18-2015 June Wednesday 
Day of month is 17 and the Month of year is 6,
also the day of year is 167 & our Weekday is 3.
The current year is 2015.

Code :

#include <ctime>
#include <iostream>
#include <string>
#include <stdio.h>
#include <time.h>

using namespace std;

const std::string currentTime() {
time_t now = time(0);
struct tm tstruct;
char buf[80];
tstruct = *localtime(&now);
strftime(buf, sizeof(buf), "%H:%M:%S %P", &tstruct);
return buf;
}

const std::string currentDate() {
time_t now = time(0);
struct tm tstruct;
char buf[80];
tstruct = *localtime(&now);
strftime(buf, sizeof(buf), "%B %A ", &tstruct);
return buf;
}

int main() {
    cout << "\033[2J\033[1;1H"; 
std:cout << "The current time is " << currentTime() << std::endl;
    time_t t = time(0);   // get time now
    struct tm * now = localtime( & t );
    cout << "The current date is " << now->tm_mon + 1 << '-' 
         << (now->tm_mday  + 1) << '-'
         <<  (now->tm_year + 1900) 
         << " " << currentDate() << endl; 

 cout << "Day of month is " << (now->tm_mday) 
      << " and the Month of year is " << (now->tm_mon)+1 << "," << endl;
    cout << "also the day of year is " << (now->tm_yday) 
         << " & our Weekday is " << (now->tm_wday) << "." << endl;
    cout << "The current year is " << (now->tm_year)+1900 << "." 
         << endl;
 return 0;  
}
Praneeth Peiris
  • 2,008
  • 20
  • 40
Anonymous
  • 31
  • 1
  • 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). – Fernando Gonzalez Sanchez Oct 28 '16 at 23:58
3

This compiled for me on Linux (RHEL) and Windows (x64) targeting g++ and OpenMP:

#include <ctime>
#include <iostream>
#include <string>
#include <locale>

////////////////////////////////////////////////////////////////////////////////
//
//  Reports a time-stamped update to the console; format is:
//       Name: Update: Year-Month-Day_of_Month Hour:Minute:Second
//
////////////////////////////////////////////////////////////////////////////////
//
//  [string] strName  :  name of the update object
//  [string] strUpdate:  update descripton
//          
////////////////////////////////////////////////////////////////////////////////

void ReportTimeStamp(string strName, string strUpdate)
{
    try
    {
        #ifdef _WIN64
            //  Current time
            const time_t tStart = time(0);
            //  Current time structure
            struct tm tmStart;

            localtime_s(&tmStart, &tStart);

            //  Report
            cout << strName << ": " << strUpdate << ": " << (1900 + tmStart.tm_year) << "-" << tmStart.tm_mon << "-" << tmStart.tm_mday << " " << tmStart.tm_hour << ":" << tmStart.tm_min << ":" << tmStart.tm_sec << "\n\n";
        #else
            //  Current time
            const time_t tStart = time(0);
            //  Current time structure
            struct tm* tmStart;

            tmStart = localtime(&tStart);

            //  Report
            cout << strName << ": " << strUpdate << ": " << (1900 + tmStart->tm_year) << "-" << tmStart->tm_mon << "-" << tmStart->tm_mday << " " << tmStart->tm_hour << ":" << tmStart->tm_min << ":" << tmStart->tm_sec << "\n\n";
        #endif

    }
    catch (exception ex)
    {
        cout << "ERROR [ReportTimeStamp] Exception Code:  " << ex.what() << "\n";
    }

    return;
}
3

Here is the non-deprecated modern C++ solution for getting a timestamp as a std::string for use with e.g. filenames:

std::string get_file_timestamp()
{
    const auto now = std::chrono::system_clock::now();
    const auto in_time_t = std::chrono::system_clock::to_time_t(now);

    std::stringstream output_stream;

    struct tm time_info;
    const auto errno_value = localtime_s(&time_info, &in_time_t);
    if(errno_value != 0)
    {
        throw std::runtime_error("localtime_s() failed: " + std::to_string(errno_value));
    }

    output_stream << std::put_time(&time_info, "%Y-%m-%d.%H_%M_%S");
    return output_stream.str();
}
BullyWiiPlaza
  • 17,329
  • 10
  • 113
  • 185
  • 1
    This is the best answer. It integrates formatting and does not show unsafe errors or buffer overrun warnings like others. – Gru Mar 01 '23 at 22:34
  • @Gru: Thanks, yeah, I'm not a fan of old school code full of warnings by state of the art IDEs and code analyzers lol – BullyWiiPlaza Mar 04 '23 at 08:55
2

The ffead-cpp provides multiple utility classes for various tasks, one such class is the Date class which provides a lot of features right from Date operations to date arithmetic, there's also a Timer class provided for timing operations. You can have a look at the same.

user775757
  • 221
  • 1
  • 3
  • 7
2

http://www.cplusplus.com/reference/ctime/strftime/

This built-in seems to offer a reasonable set of options.

bduhbya
  • 410
  • 5
  • 6
  • 1
    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. – bduhbya Aug 07 '14 at 21:19
2

localtime_s() version:

#include <stdio.h>
#include <time.h>

int main ()
{
  time_t current_time;
  struct tm  local_time;

  time ( &current_time );
  localtime_s(&local_time, &current_time);

  int Year   = local_time.tm_year + 1900;
  int Month  = local_time.tm_mon + 1;
  int Day    = local_time.tm_mday;

  int Hour   = local_time.tm_hour;
  int Min    = local_time.tm_min;
  int Sec    = local_time.tm_sec;

  return 0;
} 
sailfish009
  • 2,561
  • 1
  • 24
  • 31
1

You could use boost and chrono library:

#include <iostream>
#include <chrono>
#include <boost/date_time/posix_time/posix_time.hpp>

using boost::posix_time::to_iso_extended_string;
using boost::posix_time::from_time_t;
using std::chrono::system_clock;

int main()
{
  auto now = system_clock::now();
  std::cout << to_iso_extended_string(from_time_t(system_clock::to_time_t(now)));
}
Andreas DM
  • 10,685
  • 6
  • 35
  • 62
1
#include <iostream>
#include <chrono>
#include <string>
#pragma warning(disable: 4996)
// Ver: C++ 17 
// IDE: Visual Studio
int main() {
    using namespace std; 
    using namespace chrono;
    time_point tp = system_clock::now();
    time_t tt = system_clock::to_time_t(tp);
    cout << "Current time: " << ctime(&tt) << endl;
    return 0;
}
r3t40
  • 579
  • 6
  • 12
-1
#include <Windows.h>

void main()
{
     //Following is a structure to store date / time

SYSTEMTIME SystemTime, LocalTime;

    //To get the local time

int loctime = GetLocalTime(&LocalTime);

    //To get the system time

int systime = GetSystemTime(&SystemTime)

}
ʇolɐǝz ǝɥʇ qoq
  • 717
  • 1
  • 15
  • 30
  • 7
    The question asks for cross-platform. Windows.h is Windows-specific, and `void main` isn't even standard C/C++. – derpface Jan 16 '15 at 15:54
-3

I needed a way to insert current date-time at every update of a list. This seems to work well, simply.

#include<bits/stdc++.h>
#include<unistd.h>
using namespace std;
int main()
{   //initialize variables
    time_t now; 
    //blah..blah
    /*each time I want the updated stamp*/
    now=time(0);cout<<ctime(&now)<<"blah_blah";
}
Jan
  • 993
  • 1
  • 13
  • 28
Gary
  • 1
  • 1