Get system date

4

I am doing a program in #C for the university and I need to get the current system date to know when the person has registered.

So far to catch the date I have this:

time_t tiempo = time(NULL);//variables donde guardo el valor de la funcion time. 
    struct tm *tlocal = localtime(&tiempo); //estructura donde obtengo el tiempo 
    char output[10]; //array donde guardo la fecha
    strftime(output,10,"%d/%m/%y",tlocal); //formato para guardar la fecha obtenido en *tlocal como dd/mm/yyyy
    printf("%s\n",output);

The problem is that in doing this the date is saved correctly but the year only has 2 digits, that is, instead of saving 10/04/2017 it saves 10/04/17.

I have searched the internet to save the complete date with all the digits and I have read that if in the function strftime I put the y in uppercase it keeps the 4 digits of the year but I have tried it and it does not work for me.

Any ideas to get the system date in dd / mm / yyyy format?

    
asked by JoseCa 18495 11.04.2017 в 12:49
source

3 answers

6
char output[10];
strftime(output,10,"%d/%m/%y",tlocal);

A date in dd / mm / YYYY format takes place:

  • 2 digits (day)
  • 2 digits (month)
  • 4 digits (year)
  • 2 digits (separators)
  • 1 digit (end of string)

In total 11 characters ... and your arrangement is only 10.

What is happening is that strftime detects that the year will not enter and omits it to not write in memory areas that do not belong to your arrangement.

The solution is as simple as changing the size of the buffer to allow a minimum of 11 characters):

char output[11];
strftime(output,11,"%d/%m/%Y",tlocal);
    
answered by 11.04.2017 / 13:00
source
4

You can use the <chrono> C ++ 11 header to get the current moment and print it out by console like this:

auto now = std::chrono::system_clock::now();
auto time = std::chrono::system_clock::to_time_t(now);

std::cout << std::put_time(std::localtime(&time), "%d-%m-%Y");

This code requires the header <chrono> to access the time and header utilities < a href="http://en.cppreference.com/w/cpp/header/iomanip"> <iomanip> to transform the time values into text (in addition to <iostream> to write to the console, but that will already depend on your needs).

    
answered by 12.04.2017 в 12:23
1

The std C libraries give us the function time() . It can also be formatted in Hours: Minutes: Seconds using the functions of C.

time_t  timev;
time(&timev);
    
answered by 11.04.2017 в 13:00