1
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 localtime, ask me to use localtime_s instead. Below is my code with using localtime_s:

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 int? I print the variable with this code: cout << now.tm_year << " " << now.tm_mon << " " << now.tm_mday; but the output is -1 -1 -1

Newbie
  • 1,584
  • 9
  • 33
  • 72

2 Answers2

0

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

Community
  • 1
  • 1
-1

What I found from a different question How do you get the current time of day?

the code below will give you a string for the date. you should be able to split this and convert it to an int.

DateTime.Now.TimeOfDay gives it to you as a TimeSpan (from midnight). DateTime.Now.ToString("h:mm:ss tt") gives it to you as a string. DateTime reference: https://msdn.microsoft.com/en-us/library/system.datetime

many thanks to Mark Brackett for this answer

Community
  • 1
  • 1
hurnhu
  • 888
  • 2
  • 11
  • 30