2

Is there an easy "beginner" way to take the current time using <ctime> to a Date object that has

int month
int day
int year

for it's member variables? Thanks.

bluish
  • 26,356
  • 27
  • 122
  • 180
Crystal
  • 28,460
  • 62
  • 219
  • 393

2 Answers2

4
time_t tt = time(NULL); // get current time as time_t
struct tm* t = localtime(&tt) // convert t_time to a struct tm
cout << "Month "  << t->tm_mon 
     << ", Day "  << t->tm_mday
     << ", Year " << t->tm_year
     << endl

The tm struct ints are all 0-based (0 = Jan, 1 = Feb) and you can get various day measures, day in month (tm_mday), week (tm_wday) and year(tm_yday).

bluish
  • 26,356
  • 27
  • 122
  • 180
Robert Christie
  • 20,177
  • 8
  • 42
  • 37
2

If there is localtime_r then you should use localtime_r rather than localtime since this is the reentrant version of localtime.

#include <ctime>
#include <iostream>

int main()
{
    time_t tt = time(NULL); // get current time as time_t
    tm  tm_buf;
    tm* t = localtime_r(&tt, &tm_buf); // convert t_time to a struct tm

    std::cout << "Month "  << t->tm_mon
              << ", Day "  << t->tm_mday
              << ", Year " << t->tm_year
              << std::endl;
    return 0;
}