Home > front end >  Custom date and time including nanoseconds in C
Custom date and time including nanoseconds in C

Time:04-10

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:

//%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

CodePudding user response:

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, you can use clock_gettime():

struct timespec tv;
clock_gettime(CLOCK_REALTIME, &tv);
struct tm *timePointerEnd = localtime(&tv.tv_sec);
size_t nbytes = strftime(timeStringEnd, BUFFERSIZE, "\n%B%e, %G %T", timePointerEnd);
snprintf(timeStringEnd   nbytes, sizeof(timeStringEnd) - nbytes,
         "%.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.

  •  Tags:  
  • c
  • Related