Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Custom date and time including nanoseconds in C

For this program I need to "grab the start time of the entire process within the max. time precision avail including nanoseconds." in the format:
April 9, 2022 13:18:17.123456789

I am able to get everything but the nanoseconds. is it possible and/or what do you recommend?

Here is what I have:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

//%B - Full Month Name
//%e - day space padded (%d 0 padded)
//$G - year (with century)
//%R - 24-hour HH:MM time, equivalent to %H:%M
//%N - nanoseconds?
//%T - ISO 8601 time format (HH:MM:SS), equivalent to %H:%M:%S

            #define BUFFERSIZE 256

            char timeStringEnd[BUFFERSIZE] = {0};

            time_t timeEnd = time(NULL);

            struct tm *timePointerEnd = localtime(&timeEnd);

            strftime(timeStringEnd, BUFFERSIZE, "\n%B%e, %G %T", timePointerEnd);

            puts(timeStringEnd);

%N doesn’t want to work. Any supplemental material/sources on using timing is much appreciated . TIA

>Solution :

The strftime() function doesn’t support sub-second times. You’ll need to add that yourself. You also need to use a function that returns sub-second times — that isn’t time(). Assuming you have a POSIX-ish system:

struct timespec tv;
clock_gettime(CLOCK_REALTIME, &tv);
struct tm *timePointerEnd = localtime(&tv.tv_sec);
strftime(timeStringEnd, BUFFERSIZE, "\n%B%e, %G %T", timePointerEnd);
snprintf(timeStringEnd + strlen(timeStringEnd),
         sizeof(timeStringEnd) - strlen(timeStringEnd),
         "%.9ld", tv.tv_nsec);
puts(timeStringEnd);

C11 provides the timespec_get() function that does roughly the same job. It uses a struct timespec, but the arguments are slightly different. You’d pass the pointer first and specify TIME_UTC as the second argument.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading