Question

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.

Was it helpful?

Solution

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

OTHER TIPS

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;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top