Home > Back-end >  How to parse values from a C string into a struct timespec
How to parse values from a C string into a struct timespec

Time:02-08

My program will be receiving C string input in the format of Wed, 21 Oct 2015 07:28:00 GMT, e.g.

char * date = "Wed, 21 Oct 2015 07:28:00 GMT"

How to convert this into a struct timespec so I can compare with the st_atim, st_mtim, and st_ctim struct timespec's returned from the stat() function?

This post talks about strptime and sscanf, and I also found strftime, but all these convert to a struct time_t or struct tm or integer values.

CodePudding user response:

Look at the definition of a timespec:

struct timespec
{
  time_t tv_sec;  // Seconds
  long   tv_nsec; // Nanoseconds
};

So, it's nothing other than a time_t with an additional number of nanoseconds.

A string like you showed (Wed, 21 Oct 2015 07:28:00 GMT) doesn't even have anything more granular than seconds, so the nanoseconds will hardly matter, and you can just parse it into a time_t that goes into tv_sec and set tv_nsec to zero.

By the way the format you showed is based on the specifications outlined in RFC 822 / RFC 1123 / RFC 2822. This should make it a lot easier to search for code that parses it, for example this. This is also informally known as "HTTP date" due to its use in HTTP headers. In fact, libcurl has a function curl_getdate that parses it. You can see its C source code here.

Example:

#include <curl/curl.h>

timespec ts = {0};
ts.tv_sec = curl_getdate(inputString, NULL);

Unless you already use libcurl elsewhere, this could be an unnecessarily large overhead, but you can take it as inspiration or look for other parsing methods that give you a time_t as well.

  •  Tags:  
  • Related