从时间戳中提取时间
我正在尝试从ISO8601时间戳中提取时间段。
例如,从下面的timstamp "0001-01-01T17:45:33"
我想提取这部分"17:45:33"
。
你有几个选择。
假设你有一个名为string
的变量char数组。
现在,如果你知道时间总是在字符串的末尾,你可以很容易地做到:
#define TIMEWIDTH 8 #include #include 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); }
如果它更复杂,你必须做一些分析才能找到它。 手动或使用不同的可用工具,如sscanf()
或其他。 确保为sscanfs()
指定宽度。
http://www.tutorialspoint.com/c_standard_library/c_function_sscanf.htm
如果T
表示你可以用strchr查找它的开始时间:
#include #include int main() { const char string[] = {"0001-01-01T17:45:33\0"}; char *temp; temp = strchr(string, 'T') + 1; printf("%s\n", temp); }
这实际上取决于输入的变量如何……如果它只是一个单一的例子,你可以使用它们。 尽管最后一个更有效率。
您表明它是ISO 8601时间戳。 然后我会使用第二种方法。