tags:

views:

145

answers:

3

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

int month
int day
int year

for it's member variables? Thanks.

A: 

Se man (3) localtime

piotr
+2  A: 
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_wday).

Robert Christie
+2  A: 

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;
}
skwllsp