-2

I'm trying to extract the time section from an ISO8601 timestamp.

e.g. From the following timstamp"0001-01-01T17:45:33" I want to extract this part "17:45:33".

Arindam Nayak
  • 7,346
  • 4
  • 32
  • 48
Anis_Stack
  • 3,306
  • 4
  • 30
  • 53
  • 3
    Extract to where? How are your variables and functions are declared? – barak manos Nov 13 '14 at 17:23
  • 3
    if you want to extract from some string then you can use strstr() but it is not clear what actually you want? – Gopi Nov 13 '14 at 17:24
  • 3
    this_part = strchr(this_string, 'T')+1; – BLUEPIXY Nov 13 '14 at 17:28
  • possible duplicate of [strptime() equivalent on Windows?](http://stackoverflow.com/questions/321849/strptime-equivalent-on-windows) – AeroX Nov 13 '14 at 17:51
  • You might be better off parsing the string into a time struct so that you can then use standard library date functions to manipulate it or output it in any format you like afterwards. – AeroX Nov 13 '14 at 17:52

1 Answers1

2

you have a few options.

lets say you have it in a variable char array called string.

now if you know that it the time will always be at the end of the string it`s very easy you can just do:

#define  TIMEWIDTH    8
#include <stdio.h>
#include <string.h>

int main() {
    const char string[] = {"0001-01-01T17:45:33\0"};

    unsigned int strlength = strlen(string);

    char temp[TIMEWIDTH + 1];   // add one for null character

    printf("%s\n", string);
    strncpy(temp, string + strlength - TIMEWIDTH, TIMEWIDTH + 1);  // another + 1 for the null char
    printf("%s\n", temp);
}

if it's more complex you have to do some more analyzing to find it. either manually or use different available tools like sscanf() or something else. make sure to specifiec widths for sscanfs().

http://www.tutorialspoint.com/c_standard_library/c_function_sscanf.htm

if the T indicates the start of the time you can look for it with strchr:

#include <stdio.h>
#include <string.h>

int main() {
    const char string[] = {"0001-01-01T17:45:33\0"};

    char *temp;

    temp = strchr(string, 'T') + 1;
    printf("%s\n", temp);
}

It really depends on how variable the input is... If it is just a singular example you can use either. Allthough the last one is more efficient.

You indicated that it is an ISO 8601 timestamp. then I would just use the 2nd method.

rowan.G
  • 717
  • 7
  • 13