|
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677 |
- #include "oppgave.h"
-
- #include <stdio.h>
- #include <time.h>
-
- void datetime_init(datetime* dt)
- {
- dt->date.year = 0;
- dt->date.month = 0;
- dt->date.day = 0;
-
- dt->time.hours = 0;
- dt->time.minutes = 0;
- dt->time.seconds = 0;
- }
-
- // I expect all times to be in UTC, considering there's no timezone information
- void datetime_set_date(datetime* dt, int year, int month, int day)
- {
- dt->date.year = year;
- dt->date.month = month;
- dt->date.day = day;
- }
-
- // I expect all times to be in UTC, considering there's no timezone information
- void datetime_set_time(datetime* dt, int hours, int minutes, int seconds)
- {
- dt->time.hours = hours;
- dt->time.minutes = minutes;
- dt->time.seconds = seconds;
- }
-
- void datetime_diff(datetime* dt_from, datetime* dt_to, datetime* dt_res)
- {
- struct tm tm_from = {
- .tm_sec = dt_from->time.seconds,
- .tm_min = dt_from->time.minutes,
- .tm_hour = dt_from->time.hours,
- .tm_mday = dt_from->date.day + 1, // tm is kinda inconsistent here
- .tm_yday = -1,
- .tm_isdst = 0,
- .tm_mon = dt_from->date.month,
- .tm_year = dt_from->date.year - 1900 // tm expects years since 1900
- };
- struct tm tm_to = {
- .tm_sec = dt_to->time.seconds,
- .tm_min = dt_to->time.minutes,
- .tm_hour = dt_to->time.hours,
- .tm_mday = dt_to->date.day + 1, // Still inconsistent
- .tm_yday = -1,
- .tm_isdst = 0,
- .tm_mon = dt_to->date.month,
- .tm_year = dt_to->date.year - 1900 // Not entirely sure why it's 1900
- };
-
- time_t time_from = mktime(&tm_from);
- time_t time_to = mktime(&tm_to);
-
- time_t time_res = difftime(time_to, time_from);
-
- // Still expecting UTC, thus gmtime instead of localtime
- struct tm tm_res = *(gmtime(&time_res));
-
- dt_res->time.seconds = tm_res.tm_sec;
- dt_res->time.minutes = tm_res.tm_min;
- dt_res->time.hours = tm_res.tm_hour;
- dt_res->date.day = tm_res.tm_mday - 1;
- dt_res->date.month = tm_res.tm_mon;
- dt_res->date.year = tm_res.tm_year - 70; // Because 1970 is UNIX epoch
- }
-
- void datetime_print(datetime* dt)
- {
- printf("Year: %i, month: %i, day: %i. Hour: %i, minute: %i, second: %i.\n",
- dt->date.year, dt->date.month, dt->date.day,
- dt->time.hours, dt->time.minutes, dt->time.seconds);
- }
|