Skip to content
Advertisement

How to format unix time (sec+usec+nsec) string?

I have this function which works just fine. It gives me current system time the way I need:

JavaScript

Now I need to also be able to print timestamps I receive from 3rd party lib in 2-3 variables – sec, usec, nsec (optional). Can I somehow construct timespec from these values and reuse the code I already have?

Advertisement

Answer

You don’t need a timespec structure.

Notice how all the gmtime calls only use the tv_sec field of the structure? You can use the sec argument directly in the gmtime call.

As for the nanoseconds, you could multiply usec with 1000 to get the corresponding nanoseconds.

So something like:

JavaScript

In the third overload, just add nsec to the result of usec * 1000.


I would rather recommend you create a utility function for the creation of the string, which all the other functions are calling.

Like

JavaScript

And unless there’s code and requirements not mentioned, there’s really no need for these member functions to be non-static.

And the Timer names implies something like stop-watch, so the class should probably be renamed as well.

Advertisement