0

In my program I am trying to display today's date in a day//month//year layout. I've tried using many different ways but I keep getting errors about unsafe use of cTime.

Is there a simple way of getting my program to show the date:

time_t t = time(0);   // get time now
struct tm * now = localtime( & t );
cout << (now->tm_year + 1900) << '-' 
     << (now->tm_mon + 1) << '-'
     <<  now->tm_mday
     << endl;

I keep getting "'localtime': This function or variable may be unsafe. Consider using localtime_s instead." So I did, and now I get 'localtime_s' : function does not take 1 arguments

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740

2 Answers2

2

localtime_s is a Microsoft-specific function that is similar to the C-standard function but with slightly different arguments that are less error-prone. See http://msdn.microsoft.com/en-us/library/a442x3ye.aspx for more information.

That said, if you are using C++, it might be better to use the functions from the chrono part of the C++ standard library. They are easier to use and safe: http://en.cppreference.com/w/cpp/chrono

jeffrey_t_b
  • 1,779
  • 12
  • 18
  • Most examples of using chrono still seem to use 'time_t' and 'localtime'. So I'm not sure that using it is going to help with problem of microsoft deciding that standard library functions are depreciated. – PeterSW Dec 12 '13 at 23:52
1

Unfortunately the standard definition for functions to get from a time_t to formated text all seem to have some potential safety issues, particularly in multi-threaded programs. This leaves you with a choice between going for a vendor specific route or loosing safety in return for portability.

Microsoft specific route:

Details of localtime_s are available here: http://msdn.microsoft.com/en-us/library/a442x3ye%28v=vs.110%29.aspx

Following that something like this should work on visual studio 2012 without warning:

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

int main() {
    time_t t = time(0);   // get time now
    struct tm now;
    localtime_s(&now, &t);
    cout << (now->tm_year + 1900) << '-' 
         << (now->tm_mon + 1) << '-'
         <<  now->tm_mday
         << endl;
}

However localtime_s is microsoft specific so using it will limit the portability of your code.

Standard compliant but less safe route:

If you prefer standards compliance to safer versions you can use your original version of you code but add the following at the top of the file:

#define _CRT_SECURE_NO_WARNINGS
PeterSW
  • 4,921
  • 1
  • 24
  • 35