Pergunta
Existe uma maneira fácil para "iniciante" de calcular o tempo atual usando <ctime>
para um objeto Date que tem
int month
int day
int year
para suas variáveis de membro?Obrigado.
Solução
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
O tm
struct ints são todos baseados em 0 (0 = janeiro, 1 = fevereiro) e você pode obter várias medidas diárias, dia no mês (tm_mday
), semana (tm_wday
) e ano (tm_yday
).
Outras dicas
Se houver localtime_r então você deve usar hora local_r em vez de hora local, pois esta é a versão reentrante da 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 em: CC-BY-SA com atribuição
Não afiliado a StackOverflow