xs_time.h 2.3 KB

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