I am developing a C application on Visual Studio in which I have a string that contains a datetime value and I must convert it into another string with the date and time in the format dd-mm-yyyy HH:MM:SS
For example, if the string sDateTime has the value "1643873040", I must get another string sDateAndTime with the value "02/03/2022, 08:24:00"
I have not found any tutorials or forums that explain how to do this conversion in a C or C program developed with Visual Studio and I would appreciate any help or suggestions.
CodePudding user response:
Your value 1643873040 appears to be a Unix time value, known in C as a time_t. The first step in converting it to human-readable format is to use the function localtime, which returns a pointer to a "broken down" time structure, struct tm:
#include <stdio.h>
#include <time.h>
time_t t = 1643873040;
struct tm *tmp = localtime(&t);
Next, you can use the strftime function to create a string from the struct tm:
char strbuf[30];
strftime(strbuf, sizeof(strbuf), "%Y-%m-%d %H:%M:%S", tmp);
printf("%s\n", strbuf);
Or, you can print the fields from the struct tm directly:
printf("%d-d-d d:d:d\n",
tmp->tm_year 1900, tmp->tm_mon 1, tmp->tm_mday,
tmp->tm_hour, tmp->tm_min, tmp->tm_sec);
Here, though, you have to be careful, because the tm_mon field is 0-based, and tmp_year is offset by 1900.
A time_t value like 1643873040 usually represents UTC, also known as GMT. The localtime function takes care of converting it to your local time zone (including DST corrections, if necessary). If you want UTC time instead, without applying time zone and DST corrections, you can call gmtime instead of localtime.
This answer has been for C. Although the localtime, gmtime, and strftime functions will work fine in C also, C has its own, perhaps preferred ways of doing it.
CodePudding user response:
Take a look at chrono it should help you in dealing with time.
Also give a look at this stack overflow question and answers
