So i am getting my time from an api that returns epoch time and i need to pass that time into a Real Time Clock function which accepts this dateTime structure
datetime_t t = { // Friday June 5, Hour 15, Minute 45, Sec 00
.year = 2020,
.month = 06,
.day = 05,
.dotw = 5, // 0 is Sunday, so 5 is Friday
.hour = 15,
.min = 45,
.sec = 00
};
I need help creating a formula to get those individual values. I think i have made a formula for the easy ones.
sec = epochTime%60
min = floor((epochTime%3600)/60)
hour = floor((epochTime%86400)/3600)
as for the others it is not that easy anymore as there are leap years and such. i have to do this with only standard libraries or you can suggest a web api that returns me those value (it has to be only 1 api for all of those data)
CodePudding user response:
Assuming the epoch time is the UNIX epoch, i.e. seconds since 1970/01/01 00:00:00 UTC, you can use the localtime
function. This function takes the address of a time_t
containing epoch time and splits it into its component values, assuming the local timezone:
struct tm *tm;
time_t t = time(NULL);
tm = localtime(&t);
The returned structure is defined as follows:
struct tm {
int tm_sec; /* seconds */
int tm_min; /* minutes */
int tm_hour; /* hours */
int tm_mday; /* day of the month */
int tm_mon; /* month */
int tm_year; /* year */
int tm_wday; /* day of the week */
int tm_yday; /* day in the year */
int tm_isdst; /* daylight saving time */
};
Where tm_year
is years since 1900, tm_mon
is in the range 0-11, and tm_wday
is in the range 0-6 (Sun-Sat).
If you want UTC time, you can use gmtime
instead with the same parameters / return type.