Can someone please suggest how can I retrieve linux time using
struct timespec ts
type? It just gives me time since Epoch. Can I get the actual Linux time using this datatype?
Brief Background: I am writing a logger utility on embedded device with timestamp resolution in milli/micro seconds. The source adds timestamp which is consumed by destination component.
struct stLogItem logitem; //stLogItem has a member, struct timespec ts
clock_gettime(clk_id, &logitem.ts);
The destination component is printing this log timestamp on file/console. But the date which is printed out is time since Epoch, and not the actual Linux date.
The printed data is: 1970-01-01 23:30:07.586864475
Whereas, the Linux date is different as shown below:
root@imh:# date
Tue Nov 14 11:34:12 UTC 2017
Its not a format issue. It is about getting the current Linux time (in nano seconds).
After calling clock_gettime
, ts.tv_sec
, which has type time_t
, is populated with the timestamp in seconds since the epoch. You can pass that directly to localtime
:
struct timespec ts;
clock_gettime(clk_id, &ts);
struct tm *my_tm = localtime(&ts.tv_sec);
Now my_tm
points to a struct tm
which has the time broken down into year / month / day / hour / minute / second, and ts.tv_nsec
has the nanosecond portion.