How to get system time and save in a variable?

3

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

    
asked by anonymous 12.10.2016 / 01:02

3 answers

1
#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;
}
    
12.10.2016 / 01:06
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 much experience yet, and second because there are still some deficiencies in the standard itself, which implies the need to use the underlying infrastructure in C when it is necessary display weather information.

A schedule to display the 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';
}                                                        
    
12.10.2016 / 05:37
1

You can use the time function to return the current date and time information and localtime to represent the values according to the 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 into a string , use std::to_string :

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