Pregunta

¿Hay una manera fácil de "principiante" a tomar el tiempo actual usando <ctime> a un objeto Date que tiene

int month
int day
int year

para las variables miembros, de? Gracias.

¿Fue útil?

Solución

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

Los enteros tm struct son todos 0-basa (0 =-ene-1 = febrero) y se puede obtener diversas medidas de día, el día en el mes (tm_mday), la semana (tm_wday) y el año (tm_yday).

Otros consejos

Si hay localtime_r, entonces debería usar localtime_r en lugar de localtime ya que esta es la versión de reentrada de hora local.

#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;
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top