You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言中将ISO格式ASCII日期数组转为DD-MM-YYYY HHmmss的方法

问题:C语言中解析ISO8601日期字符串并转换格式

我有一个对应ISO8601格式(2023-04-26T12:01:42.123+01:00)的ASCII字节数组,字节内容如下:

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(解析ASCII字节并截断多余部分)。

我尝试了如下代码但存在问题,想知道C语言中是否有合适的实现函数,是否不该使用struct tm,还是只能逐个解析字符数组?

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

问题分析与解决方法

你的代码问题核心是strptime的格式串不匹配原日期结构,导致解析失败。struct tm是完全可以用的,只要正确使用标准库函数或针对场景做适配。

1. 正确使用strptime与struct tm的方案

C标准库的strptime支持解析ISO8601格式,关键是要写对格式匹配串:
原日期格式为YYYY-MM-DDTHH:MM:SS.sss+HH:MM,对应的strptime格式串应为"%Y-%m-%dT%H:%M:%S.%f%z"(%f匹配毫秒部分,%z匹配时区偏移,GNU等主流实现均支持)。

修改后的可运行代码:

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

void convertUTCTimeto24HourFormat(const void* data)
{
    char buf[sizeof "24-04-2023 245957"];
    struct tm tm_struct = {0};
    const char* date_str = (const char*)data;

    // 解析包含毫秒和时区的ISO8601字符串
    if (strptime(date_str, "%Y-%m-%dT%H:%M:%S.%f%z", &tm_struct) != NULL) {
        strftime(buf, sizeof(buf), "%d-%m-%Y %H%M%S", &tm_struct);
        printf("转换结果:%s\n", buf);
    } else {
        printf("日期解析失败\n");
    }
}

// 测试示例
int main() {
    const char test_date[] = "2023-04-26T12:01:42.123+01:00";
    convertUTCTimeto24HourFormat(test_date);
    return 0;
}

2. 针对特殊环境的适配

如果你的环境不支持%z(比如部分嵌入式系统),可以手动截断时区部分后再解析:

// 截断时区,仅保留到毫秒前的内容
char temp_buf[30];
strncpy(temp_buf, date_str, strcspn(date_str, "+"));
temp_buf[strcspn(date_str, "+")] = '\0';
// 用不含时区的格式串解析
strptime(temp_buf, "%Y-%m-%dT%H:%M:%S.%f", &tm_struct);

3. 手动解析字符数组的方案

如果无法依赖标准库的日期解析函数,可直接从字节数组提取固定位置的字符拼接格式,适合资源受限的场景:

void manualConvert(const void* data) {
    const unsigned char* bytes = (const unsigned char*)data;
    char buf[20];
    // 按固定位置提取ASCII字符,拼接目标格式
    snprintf(buf, sizeof(buf), "%c%c-%c%c-%c%c%c%c %c%c%c%c%c%c",
             bytes[8], bytes[9],    // DD
             bytes[5], bytes[6],    // MM
             bytes[0], bytes[1], bytes[2], bytes[3], // YYYY
             bytes[11], bytes[12],  // HH
             bytes[14], bytes[15],  // MM
             bytes[17], bytes[18]); // SS
    printf("手动转换结果:%s\n", buf);
}

内容的提问来源于stack exchange,提问作者Iti Tyagi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 12:27:38