Ah Yong Ah Yong - 10 months ago 70
C++ Question

get current date with localtime_s

time_t t = time(0);
struct tm *now = localtime(&t);

With the code above, I can simply get the date like this:

int yearNow = (now.tm_year + 1900), monthNow = (now.tm_mon + 1), dayNow = now.tm_mday

but Visual Studio 2015 gives me error on
, ask me to use
instead. Below is my code with using

time_t rawtime;
struct tm now;
localtime_s(&now, &rawtime);

But the problem is, how do I get the actual current year, month, day in
I print the variable with this code:
cout << now.tm_year << " " << now.tm_mon << " " << now.tm_mday;

but the output is
-1 -1 -1

Answer Source

The time_t variable should be initialized with time(&rawtime) such that localtime_s can use it to properly fill out the struct. Much like your very first line time_t t = time(0), it's required that you initialize the variable with the time function and pass it a null parameter (0) or a pointer to variable (&rawtime).

Unfortunately allocating a time_t var within memory does not automatically calculate the time since Epoch. Here's a question that addresses the same problem, except it has an example of the code you're looking for.