ua_clock.c 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. /* This work is licensed under a Creative Commons CCZero 1.0 Universal License.
  2. * See http://creativecommons.org/publicdomain/zero/1.0/ for more information.
  3. *
  4. * Copyright 2016-2017 (c) Julius Pfrommer, Fraunhofer IOSB
  5. * Copyright 2017 (c) Stefan Profanter, fortiss GmbH
  6. * Copyright 2017 (c) Thomas Stalder
  7. */
  8. #ifndef _DEFAULT_SOURCE
  9. # define _DEFAULT_SOURCE
  10. #endif
  11. /* On older systems we need to define _BSD_SOURCE.
  12. * _DEFAULT_SOURCE is an alias for that. */
  13. #ifndef _BSD_SOURCE
  14. # define _BSD_SOURCE
  15. #endif
  16. #include <time.h>
  17. #include <sys/time.h>
  18. #include "ua_types.h"
  19. UA_DateTime UA_DateTime_now(void){
  20. struct timeval tv;
  21. gettimeofday(&tv, NULL);
  22. return (tv.tv_sec * UA_DATETIME_SEC) + (tv.tv_usec * UA_DATETIME_USEC) + UA_DATETIME_UNIX_EPOCH;
  23. }
  24. /* Credit to https://stackoverflow.com/questions/13804095/get-the-time-zone-gmt-offset-in-c */
  25. UA_Int64 UA_DateTime_localTimeUtcOffset(void){
  26. time_t gmt, rawtime = time(NULL);
  27. struct tm *ptm;
  28. struct tm gbuf;
  29. ptm = gmtime_r(&rawtime, &gbuf);
  30. // Request that mktime() looksup dst in timezone database
  31. ptm->tm_isdst = -1;
  32. gmt = mktime(ptm);
  33. return (UA_Int64) (difftime(rawtime, gmt) * UA_DATETIME_SEC);
  34. }
  35. UA_DateTime UA_DateTime_nowMonotonic(void) {
  36. struct timespec ts;
  37. #if !defined(CLOCK_MONOTONIC_RAW)
  38. clock_gettime(CLOCK_MONOTONIC, &ts);
  39. #else
  40. clock_gettime(CLOCK_MONOTONIC_RAW, &ts);
  41. #endif
  42. return (ts.tv_sec * UA_DATETIME_SEC) + (ts.tv_nsec / 100);
  43. }