xs_time.h 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /* copyright (c) 2022 - 2023 grunfink / 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_time(const char *str, const char *fmt, int local);
  9. #define xs_parse_localtime(str, fmt) xs_parse_time(str, fmt, 1)
  10. #define xs_parse_utctime(str, fmt) xs_parse_time(str, fmt, 0)
  11. xs_str *xs_str_time_diff(time_t time_diff);
  12. #ifdef XS_IMPLEMENTATION
  13. xs_str *xs_str_time(time_t t, const char *fmt, int local)
  14. /* returns a string with a formated time */
  15. {
  16. struct tm tm;
  17. char tmp[64];
  18. if (t == 0)
  19. t = time(NULL);
  20. if (local)
  21. localtime_r(&t, &tm);
  22. else
  23. gmtime_r(&t, &tm);
  24. strftime(tmp, sizeof(tmp), fmt, &tm);
  25. // printf("%d %d\n", local, t - xs_parse_time(tmp, fmt, local));
  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. struct tm tm;
  41. memset(&tm, '\0', sizeof(tm));
  42. strptime(str, fmt, &tm);
  43. /* try to guess the Daylight Saving Time */
  44. if (local)
  45. tm.tm_isdst = -1;
  46. return local ? mktime(&tm) : timegm(&tm);
  47. }
  48. #endif /* XS_IMPLEMENTATION */
  49. #endif /* _XS_TIME_H */