Extracting time from timestamp

梦想与她 提交于 2019-12-20 07:58:04

问题


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".


回答1:


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.



来源:https://stackoverflow.com/questions/26914695/extracting-time-from-timestamp

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