xs_time.h 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. return xs_str_new(tmp);
  26. }
  27. xs_str *xs_str_time_diff(time_t time_diff)
  28. /* returns time_diff in seconds to 'human' units (d:hh:mm:ss) */
  29. {
  30. int secs = time_diff % 60;
  31. int mins = (time_diff /= 60) % 60;
  32. int hours = (time_diff /= 60) % 24;
  33. int days = (time_diff /= 24);
  34. return xs_fmt("%d:%02d:%02d:%02d", days, hours, mins, secs);
  35. }
  36. char *strptime(const char *s, const char *format, struct tm *tm);
  37. time_t xs_parse_time(const char *str, const char *fmt, int local)
  38. {
  39. struct tm tm;
  40. memset(&tm, '\0', sizeof(tm));
  41. strptime(str, fmt, &tm);
  42. /* try to guess the Daylight Saving Time */
  43. if (local)
  44. tm.tm_isdst = -1;
  45. return local ? mktime(&tm) : timegm(&tm);
  46. }
  47. #endif /* XS_IMPLEMENTATION */
  48. #endif /* _XS_TIME_H */