University stuff.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

oppgave.c 2.1KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. #include "oppgave.h"
  2. #include <stdio.h>
  3. #include <time.h>
  4. void datetime_init(datetime* dt)
  5. {
  6. dt->date.year = 0;
  7. dt->date.month = 0;
  8. dt->date.day = 0;
  9. dt->time.hours = 0;
  10. dt->time.minutes = 0;
  11. dt->time.seconds = 0;
  12. }
  13. // I expect all times to be in UTC, considering there's no timezone information
  14. void datetime_set_date(datetime* dt, int year, int month, int day)
  15. {
  16. dt->date.year = year;
  17. dt->date.month = month;
  18. dt->date.day = day;
  19. }
  20. // I expect all times to be in UTC, considering there's no timezone information
  21. void datetime_set_time(datetime* dt, int hours, int minutes, int seconds)
  22. {
  23. dt->time.hours = hours;
  24. dt->time.minutes = minutes;
  25. dt->time.seconds = seconds;
  26. }
  27. void datetime_diff(datetime* dt_from, datetime* dt_to, datetime* dt_res)
  28. {
  29. struct tm tm_from = {
  30. .tm_sec = dt_from->time.seconds,
  31. .tm_min = dt_from->time.minutes,
  32. .tm_hour = dt_from->time.hours,
  33. .tm_mday = dt_from->date.day + 1, // tm is kinda inconsistent here
  34. .tm_yday = -1,
  35. .tm_isdst = 0,
  36. .tm_mon = dt_from->date.month,
  37. .tm_year = dt_from->date.year - 1900 // tm expects years since 1900
  38. };
  39. struct tm tm_to = {
  40. .tm_sec = dt_to->time.seconds,
  41. .tm_min = dt_to->time.minutes,
  42. .tm_hour = dt_to->time.hours,
  43. .tm_mday = dt_to->date.day + 1, // Still inconsistent
  44. .tm_yday = -1,
  45. .tm_isdst = 0,
  46. .tm_mon = dt_to->date.month,
  47. .tm_year = dt_to->date.year - 1900 // Not entirely sure why it's 1900
  48. };
  49. time_t time_from = mktime(&tm_from);
  50. time_t time_to = mktime(&tm_to);
  51. time_t time_res = difftime(time_to, time_from);
  52. // Still expecting UTC, thus gmtime instead of localtime
  53. struct tm tm_res = *(gmtime(&time_res));
  54. dt_res->time.seconds = tm_res.tm_sec;
  55. dt_res->time.minutes = tm_res.tm_min;
  56. dt_res->time.hours = tm_res.tm_hour;
  57. dt_res->date.day = tm_res.tm_mday - 1;
  58. dt_res->date.month = tm_res.tm_mon;
  59. dt_res->date.year = tm_res.tm_year - 70; // Because 1970 is UNIX epoch
  60. }
  61. void datetime_print(datetime* dt)
  62. {
  63. printf("Year: %i, month: %i, day: %i. Hour: %i, minute: %i, second: %i.\n",
  64. dt->date.year, dt->date.month, dt->date.day,
  65. dt->time.hours, dt->time.minutes, dt->time.seconds);
  66. }