for a Date object that has int month int ...">

Parse localtime in C ++

Is there a simple "beginner" way to use the current time using <ctime>

for a Date object that has

int month
int day
int year

      

for its member variables? Thanks.

+2


a source to share


2 answers


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

      



Structural ints tm

are 0-based (0 = Jan, 1 = Feb), and you can get different daily measures, day by month ( tm_mday

), week ( tm_wday

) and year ( tm_yday

).

+4


a source


If localtime_r is present, you should use localtime_r and not localtime, as this is a reentrant version of local time.



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

      

+2


a source







All Articles