【问题标题】:Extracting time from timestamp从时间戳中提取时间
【发布时间】:2015-01-10 22:35:52
【问题描述】:

我正在尝试从 ISO8601 时间戳中提取时间部分。

例如从下面的timstamp"0001-01-01T17:45:33"我想提取这部分"17:45:33"

【问题讨论】:

  • 解压到哪里?你的变量和函数是如何声明的?
  • 如果你想从某个字符串中提取,那么你可以使用 strstr() 但不清楚你到底想要什么?
  • this_part = strchr(this_string, 'T')+1;
  • 您最好将字符串解析为时间结构,以便之后可以使用标准库日期函数对其进行操作或以您喜欢的任何格式输出。

标签: c timestamp substring iso8601


【解决方案1】:

你有几个选择。

假设您将它放在一个名为 string 的变量 char 数组中。

现在,如果您知道时间总是在字符串的末尾,那么您可以很容易地做到:

#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);
}

如果它更复杂,您必须进行更多分析才能找到它。手动或使用不同的可用工具,如sscanf() 或其他东西。确保为sscanfs() 指定宽度。

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

如果T 表示时间的开始,您可以使用 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);
}

这真的取决于输入的可变性......如果它只是一个单一的例子,你可以使用任何一个。虽然最后一种效率更高。

您指出它是 ISO 8601 时间戳。那我就用第二种方法了。

【讨论】:

    猜你喜欢
    • 2016-08-10
    • 2021-02-18
    • 1970-01-01
    • 2018-04-17
    • 1970-01-01
    • 1970-01-01
    • 2018-07-18
    • 2018-02-02
    • 2017-03-09
    相关资源
    最近更新 更多