xs_time.h 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. /* copyright (c) 2022 - 2024 grunfink et al. / MIT license */
  2. #ifndef _XS_TIME_H
  3. #define _XS_TIME_H
  4. #include <time.h>
  5. xs_str *xs_str_time(time_t t, const char *fmt, int local);
  6. #define xs_str_localtime(t, fmt) xs_str_time(t, fmt, 1)
  7. #define xs_str_utctime(t, fmt) xs_str_time(t, fmt, 0)
  8. #define xs_str_iso_date(t) xs_str_time(t, "%Y-%m-%dT%H:%M:%SZ", 0)
  9. time_t xs_parse_iso_date(const char *iso_date, int local);
  10. time_t xs_parse_time(const char *str, const char *fmt, int local);
  11. #define xs_parse_localtime(str, fmt) xs_parse_time(str, fmt, 1)
  12. #define xs_parse_utctime(str, fmt) xs_parse_time(str, fmt, 0)
  13. xs_str *xs_str_time_diff(time_t time_diff);
  14. #ifdef XS_IMPLEMENTATION
  15. xs_str *xs_str_time(time_t t, const char *fmt, int local)
  16. /* returns a string with a formated time */
  17. {
  18. struct tm tm;
  19. char tmp[64];
  20. if (t == 0)
  21. t = time(NULL);
  22. if (local)
  23. localtime_r(&t, &tm);
  24. else
  25. gmtime_r(&t, &tm);
  26. strftime(tmp, sizeof(tmp), fmt, &tm);
  27. return xs_str_new(tmp);
  28. }
  29. xs_str *xs_str_time_diff(time_t time_diff)
  30. /* returns time_diff in seconds to 'human' units (d:hh:mm:ss) */
  31. {
  32. int secs = time_diff % 60;
  33. int mins = (time_diff /= 60) % 60;
  34. int hours = (time_diff /= 60) % 24;
  35. int days = (time_diff /= 24);
  36. return xs_fmt("%d:%02d:%02d:%02d", days, hours, mins, secs);
  37. }
  38. char *strptime(const char *s, const char *format, struct tm *tm);
  39. time_t xs_parse_time(const char *str, const char *fmt, int local)
  40. {
  41. time_t t = 0;
  42. #ifndef WITHOUT_STRPTIME
  43. struct tm tm = {0};
  44. strptime(str, fmt, &tm);
  45. /* try to guess the Daylight Saving Time */
  46. if (local)
  47. tm.tm_isdst = -1;
  48. t = local ? mktime(&tm) : timegm(&tm);
  49. #endif /* WITHOUT_STRPTIME */
  50. return t;
  51. }
  52. time_t xs_parse_iso_date(const char *iso_date, int local)
  53. /* parses a YYYY-MM-DDTHH:MM:SS date string */
  54. {
  55. time_t t = 0;
  56. #ifndef WITHOUT_STRPTIME
  57. t = xs_parse_time(iso_date, "%Y-%m-%dT%H:%M:%S", local);
  58. #else /* WITHOUT_STRPTIME */
  59. struct tm tm = {0};
  60. if (sscanf(iso_date, "%d-%d-%dT%d:%d:%d",
  61. &tm.tm_year, &tm.tm_mon, &tm.tm_mday,
  62. &tm.tm_hour, &tm.tm_min, &tm.tm_sec) == 6) {
  63. tm.tm_year -= 1900;
  64. tm.tm_mon -= 1;
  65. if (local)
  66. tm.tm_isdst = -1;
  67. t = local ? mktime(&tm) : timegm(&tm);
  68. }
  69. #endif /* WITHOUT_STRPTIME */
  70. return t;
  71. }
  72. #endif /* XS_IMPLEMENTATION */
  73. #endif /* _XS_TIME_H */