how to parse syslog timestamp

百般思念 提交于 2019-12-04 11:34:34
asc99c

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!