c++c++-chronodeprecation-warninglocaltimectime

Resolving the issue of unsafe function deprecation and misusing time-getting methods like std::ctime() or std::localtime() to get local time in C++


I'm building a simple small program for fun, to kill time and learn something. I simply want my program to display local time (I live in Buffalo, NY, so I'm in ET). I put together an ostensibly ridiculous soup of libraries to ensure that my program is aware of everything:

#include <iostream>
#include <chrono>
#include <ctime> 
#include <cstdlib>

#ifdef __unix__
# include <unistd.h>
#elif defined _WIN32
# include <windows.h>
#define sleep(x) Sleep(1000 * (x))
#endif
  1. I tried the code from this page that uses the localtime() method:
#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";
}
  1. I also tried a chunk of code that uses the ctime() method from here > How to get current time and date in C++? :
#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;
}

Every time I try something, my efforts are accompanied with the compiler stating the following:

Error   C4996   'localtime': This function or variable may be unsafe. Consider using localtime_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details. 15Puzzle    C:\Users\owner\source\repos\15Puzzle\main.cpp   10  

... and when I follow that suggestion, the compiler states that the std library does not have the recommended method. I really don't want to disable anything cautionary.

What should I do?


Solution

  • (Ideas for the answer were contributed by Adrian Mole and n. 1.8e9-where's-my-share m. in the comments to the OP question.)

    The C4996 is simply a stumbling block designed by Microsoft. To bypass this "error", simply set the _CRT_SECURE_NO_WARNINGS flag to true by adding the following to the very top of the main file:

    #define _CRT_SECURE_NO_WARNINGS 1

    There seems to be more than one theory as to why Microsoft would do this, but the truth is that there's really nothing wrong with using the chrono library's traditional functions.