Show current date and time in C ++

1

I am using Visual Studio 2015 and I want to show the "date" and the "current time" in C ++, for this I am calling the functions: getLocalTime and getTimeFormat.

I have this code inside the main:

printf(GetLocalTime);
printf(GetTimeFormat);

And when I run it, it shows me the following on the screen:

ÿ00B3104BlötÌÌÌÌÌÌÌÌÌÌ<ÿU<ìQ¡¼Pöt3Å%EüV<5üWöt.ö._U

What can I do to show it on the screen?

    
asked by Daniel Ruiz 05.11.2016 в 17:21
source

3 answers

1

As you do, you are not called to the function GetLocalTime (or GetTimeFormat ), you are sending to printf the memory address of the function (you pass the name of the function directly), when printf expects its first parameter to be a string of characters. Therefore, in your code, printf is treating the memory address of the function, as if it were a string of characters, hence it prints you strange things. You should do something like (according to how little I've looked at the Windows documentation, note that those functions are not standard C , and I do not understand why they require you to do it that way):

// lo suficientemente grande para obtener el formato. La doc de 
// windows, como no, no especifica como de grande debe ser.
char formato[30]; 
int status = getTimeFormat(LOCALE_CUSTOM_DEFAULT,
      TIME_FORCE24HOURFORMAT, NULL, NULL, formato, 30);

if (status == 0)
   printf("Error. Aun estoy aprendiendo.");
else
   printf("%s", formato);

printf("\n");
    
answered by 06.11.2016 / 03:28
source
4

In C ++ 11 you can use std::put_time of the header iomanip :

#include <iostream>
#include <iomanip>
#include <ctime>

int main()
{
    auto t = std::time(nullptr);
    auto tm = *std::localtime(&t);
    std::cout << std::put_time(&tm, "%d-%m-%Y %H-%M-%S") << std::endl;
}

std::put_time is a stream manipulator , so it can also be used together with std::ostringstream to convert a date into a character string:

#include <iostream>
#include <iomanip>
#include <ctime>
#include <sstream>

int main()
{
    auto t = std::time(nullptr);
    auto tm = *std::localtime(&t);

    std::ostringstream oss;
    oss << std::put_time(&tm, "%d-%m-%Y %H-%M-%S");
    auto str = oss.str();

    std::cout << str << std::endl;
}

Taken from Current date and time as string answer in StackOverflow

    
answered by 05.11.2016 в 18:12
0

I recommend using the library time.h:

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

int main(){
    char fecha[25];//ctime devuelve 26 caracteres pero tambien se podría usar un puntero de char
    time_t current_time;
    current_time=time(NULL);
    ctime(&current_time);
    strcpy(fecha, ctime(&current_time));
    printf("%s", fecha);
    return 0;
}
    
answered by 05.11.2016 в 17:39