我有一个 ASCII 数组(转换后的字符串日期格式 2023-26-04T12:01:42.123+01:00) 字节数组现在是:
2023-04-26T12:01:42.123+01:00
32 30 32 33 2D 30 34 2D 32 36 54 30 39 3A 31 31 3A 35 37 2E 39 36 37 2B 30 39 3A 31 31
最后日期的格式必须是
DD-MM-YYYY HHmmss (parse ascii bytes and trim).
C中有没有什么函数可以帮助转换。 到目前为止我已经完成了,但似乎不正确:
void convertUTCTimeto24HourFormat(const void* data)
{
char buf[sizeof "24-04-2023 245957"]; //sample to know size
struct tm tm;
/* 1. Convert buffer to time struct */
memset(&tm, 0, sizeof(struct tm));
/* 2. strip the time and zone from data */
(void)strptime(data, "%FT%TZ", &tm);
strftime(buf, sizeof(buf), "%d-%m-%Y %H%M%S", &tm);
}
struct tm 不是这样吗?或者创建 char 数组并一个一个解析(从 ascii 到 hex 的转换似乎很乏味)
问题
(void)strptime(data, "%FT%TZ", &tm);
strptime()
不是标准的 C 库函数。各种系统定义它像this.
"%FT%TZ"
可能应该是"%FT%T%z"
:添加%
,z
用于偏移,而不是Z
名称。
忽略返回值。好的代码会检查返回值是否有错误。
OP 的ASCII 数组 缺少
strptime()
所需的空字符。
未经测试的替代品:
// Return error flag
int convertUTCTimeto24HourFormat(size_t buf_size, char *buf, const void* data) {
// Copy buf and append a \0
char source[sizeof "2023-04-26T12:01:42.123+01:00"];
strncpy(source, data, sizeof source - 1);
source[sizeof source - 1] = '\0';
// Parse string
char buf[sizeof "24-04-2023 245957"];
struct tm tm = { 0 };// Use this instead of memset().
if (strptime(source, "%FT%T%z", &tm) == NULL) {
return 1;
}
// Form new string.
if (strftime(buf, sizeof(buf), "%d-%m-%Y %H%M%S", &tm) == 0) {
return 2;
}
puts(buf);
return 0;
}
参考:ISO-8601.
假设OP的错字:
(converted String date format 2023-26-04T12:01:42.123+01:00)
(converted String date format 2023-04-26T12:01:42.123+01:00)
OP 的示例字节数组有问题
04-26T12:01:42.123+01:00
32 30 32 33 2D 30 34 2D 32 36 54 30 39 3A 31 31 3A 35 37 2E 39 36 37 2B 30 39 3A 31 31
我怀疑它是相反的
2 0 2 3 - 0 4 - 2 6 T 0 9 : 1 1 : 5 7 . 9 6 7 + 0 9 : 1 1
32 30 32 33 2D 30 34 2D 32 36 54 30 39 3A 31 31 3A 35 37 2E 39 36 37 2B 30 39 3A 31 31