2
#include <chrono>
#include <string>
#include <iostream>
#include <ctime>

using namespace std;

int main() {
    chrono::time_point<chrono::system_clock> end;
    end = chrono::system_clock::now();
    time_t end_time = chrono::system_clock::to_time_t(end);
    cout << ctime(&end_time) << endl;
    system("PAUSE");
    return 0;
} 

In C++11, how do I get the system time? When I run this code, I get an error

Code C4996 'ctime': This function or variable may be unsafe.

Also, I'd appreciate it if someone could explain to me how to adjust it so that the time is formatted in a way similar to month/day/year Hour:Minute.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Marty
  • 51
  • 7
  • 3
    Possible duplicate of [error C4996: 'ctime': This function or variable may be unsafe](https://stackoverflow.com/questions/13550864/error-c4996-ctime-this-function-or-variable-may-be-unsafe) – Daniel Langr Oct 16 '18 at 05:49
  • 1
    Note that the accepted answer is not the most upvoted. – Daniel Langr Oct 16 '18 at 05:50
  • 3
    This looks like a good time (snicker) for [Howard Hinnant's Date Library](https://github.com/HowardHinnant/date). – user4581301 Oct 16 '18 at 05:56
  • Possible duplicate of [How to convert std::chrono::time\_point to string](https://stackoverflow.com/questions/34857119/how-to-convert-stdchronotime-point-to-string) – VLL Oct 16 '18 at 07:16

1 Answers1

4

This is made much easier in C++20. In C++11, you can use Howard Hinnant's date/time library to start using the C++20 syntax today:

#include "date/date.h"
#include <chrono>
#include <iostream>

int
main()
{
    using namespace std;
    cout << date::format("%m/%d/%Y %H:%M\n", chrono::system_clock::now());
}

This outputs your system time in your desired format. Your system keeps UTC time, not local time. This just output for me:

10/16/2018 13:32

If you don't need local time / time zone support, this is a single header, header-only library. Just include date/date.h and you're good to go. If you need time zone support, there is an additional time zone library at the same link, but it is not header-only. It has one source tz.cpp that must be compiled. It can be used like this:

#include "date/tz.h"
#include <chrono>
#include <iostream>

int
main()
{
    using namespace std;
    cout << date::format("%m/%d/%Y %H:%M\n",
            date::make_zoned(date::current_zone(), chrono::system_clock::now()));
}

which for me changes the output to:

10/16/2018 09:32

This code (both examples) will port to C++20 by removing the #include "date/...", changing date::format to chrono::format, and changing date::make_zoned to chrono::zoned_time. If you have C++17, you can change date::make_zoned to date::zoned_time today (requires C++17 template deduction guides).

Howard Hinnant
  • 206,506
  • 52
  • 449
  • 577