How to take system time and save in a variable?

Asked

Viewed 8,575 times

3

How to pick the current time and save to a variable in c++?

4 answers

3

To just "save" the current C++ way of doing is

#include <chrono>
using namespace std::chrono;
...
...
auto now = system_clock::now();

To work with this new infrastructure is a little more complicated, first because there is not yet much experience, and second because there are still some deficiencies in the pattern itself, which entails the need to avail itself of the underlying infrastructure in C when it is necessary to display information on time.

A program to show current date and time:

#include <chrono>
#include <iostream>

#include <iomanip> // para put_time

using namespace std;
using namespace std::chrono;

int main()
{
   auto now = system_clock::now();
   time_t t = system_clock::to_time_t(now); // poderia ser auto t = ...
   cout << put_time(localtime(&t), "%c") << '\n';
}                                                        

2


#include <stdio.h>
#include <time.h>

int main ()
{
  time_t rawtime;
  struct tm * timeinfo;

  time ( &rawtime );
  timeinfo = localtime ( &rawtime );
  printf ( "Data atual do sistema é: %s", asctime (timeinfo) );

  return 0;
}

1

You can use the function time to return the current date and time information and localtime to represent values according to local time zone.

#include <iostream>
#include <ctime>

using namespace std;

int main()
{
  time_t timer;
  struct tm *horarioLocal;

  time(&timer); // Obtem informações de data e hora
  horarioLocal = localtime(&timer); // Converte a hora atual para a hora local

  int dia = horarioLocal->tm_mday;
  int mes = horarioLocal->tm_mon + 1;
  int ano = horarioLocal->tm_year + 1900;

  int hora = horarioLocal->tm_hour;
  int min  = horarioLocal->tm_min;
  int sec  = horarioLocal->tm_sec;

  cout << "Horário: " << hora << ":" << min << ":" << sec << endl;
  cout << "Data: "    << dia  << "/" << mes << "/" << ano << endl;

  return 0;
}

See DEMO

To put the time in a string, use the std::to_string:

// C++11
std::string horario = std::to_string(hora) + ":" + std::to_string(min) + ":" + std::to_string(sec);

-1

 #include <stdio.h>
 #include <stdlib.h>
 #include <unistd.h>
 #include <time.h>

int main(){
struct tm *data_hora_atual;
time_t t = time(NULL);//inicializa a variável time com os segundos até o momento da execução
data_hora_atual = localtime(&t);
printf ("%s", asctime (data_hora_atual) );

return 0;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.