4

http://www.syslog.cc/ietf/drafts/draft-ietf-syslog-protocol-23.txt

6.2.3.1. Examples in the above link provides examples of different timestamp formates.

How can I parse these timestamps in C?

On-the-fly, any type of message can arrive and I want to be able to parse it.

hari
  • 9,439
  • 27
  • 76
  • 110

1 Answers1

6

The date format is a stricter version of RFC3339 giving a string such as '2011-08-18T23:31:42Z'

I'm not certain the strptime function can deal with the timezone specifier (Z in the time string above), so it may be easier to handle that inside your own function. It definitely can't handle fractional seconds, since struct tm doesn't handle them. You could use struct timespec to store the fractional seconds if required.

You can parse out most of the format using strptime:

struct tm tm;
time_t t
char *extra;
extra = strptime( tmstr, "%C%y-%m-%dT%H:%M:%S", &tm );
tm.tm_isdst = -1;
t = mktime( &tm );

Following this, extra will be the remainder of the input tmstr. This could include fractional seconds, and will then contain the timezone format. If extra begins with a '.' just parse the number out with the strtod function:

if( extra && extra[0] == '.' )
{
  char *endptr;
  fraction = strtod( extra, &endptr );
  extra = endptr;

  /* use timespec if fractional seconds required */
  struct timespec ts;
  ts.tv_sec = t;
  ts.tv_nsec = fraction * 1000000000;
}

Then extra will now just contain the timezone specifier. If it is 'Z' then we're done since mktime gives you UTC time anyway. Otherwise you'll have an offset e.g. +03:00, so you will need to modify your time by that number of hours/minutes.

John Hascall
  • 9,176
  • 6
  • 48
  • 72
asc99c
  • 3,815
  • 3
  • 31
  • 54
  • Thanks a lot. This is perfect. I just need to find out how to add `+03:00` to time which I keep as `time_t`. – hari Aug 18 '11 at 23:33
  • Got it. I truly appreciate your help. – hari Aug 18 '11 at 23:44
  • 2
    `struct timespec` would be a better way to store timestamps than `double`. The latter loses precision with the passage of time, and cannot store exact representations of the "original values" which are almost surely in microseconds or nanoseconds, not some base-2 fractional form. – R.. GitHub STOP HELPING ICE Aug 19 '11 at 01:21
  • Also agree with that! After 9 years, I've just got used to how we do it, and actually it is good enough for our purposes (we only need millisecond precision). I'll edit my answer so future visitors get a better answer ... – asc99c Aug 19 '11 at 21:43
  • Isn't doing the mktime() before the timezone adjustment a source of errors (when the adjustment would move the time in to or out of "savings" time)? – John Hascall Dec 08 '15 at 16:48