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).
Seeing @dbush's answer is exactly what I needed to see to learn how to convert Linux timestamps to usable local times!
I took it further though and printed the timestamp output in more ways, including in human-readable strings with day, month, year, etc., like this:
Fri Apr 15 14:05:12 2022 -0700
.Here is the full source code, from my eRCaGuy_hello_world repo:
timing_clock_gettime_full_demo.c
Sample build and run command, and output:
The above code is part of my more-thorough answer here: How to read an NTP-adjusted RTC (Real-time clock) timestamp on Linux