【问题标题】:Regarding timestamp in C关于C中的时间戳
【发布时间】:2025-12-29 05:25:12
【问题描述】:

我正在尝试获取 YYYY-MM-DDTHH:MM:SS.SSS+HH:MM 格式的时间戳,例如2021-10-28T07:31:56.345+05:30。我能达到的最接近的是2021-11-03T13:06:43+0530。注意秒字段后面缺少的SSS0530 中缺少的:。这就是我所做的:

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

void current_time(char* str)
{
        time_t timer;
        struct tm* tm_info;

        time(&timer);
        tm_info = localtime(&timer);

        strftime(str, 50, "%FT%T%z", tm_info);
}

int main(void)
{
        char str[50];
        current_time(str);
        printf("%s\n", str);
}

任何帮助将不胜感激。谢谢。

【问题讨论】:

  • 您阅读过strftime 的文档吗?
  • @paddy 我在strftime 的手册页中找不到任何东西来实现这一点。
  • @babon 您是否还检查了struct tm 包含哪些信息?顺便说一句:看看gettimeofday

标签: c timestamp iso8601


【解决方案1】:

也许您可以使用 timespec_get 获取包括纳秒在内的时间。

#include <stdio.h>
#include <time.h>
 
void current_time(char* str, size_t len) {
    if(len < 30) { // the final string is 29 chars + '\0'
        str[0] = '\0';
        return;
    }

    struct timespec ts;
    // get timestamp inc. nanoseconds
    timespec_get(&ts, TIME_UTC);

    // get the second part of the timespec:
    struct tm lt = *localtime(&ts.tv_sec);

    // format the beginning of the string
    size_t w = strftime(str, len, "%FT%T.", &lt);

    // add milliseconds
    w += sprintf(str + w, "%03d", (int)(ts.tv_nsec / 1000000));
    
    // get zone offset from UTC 
    char zone[6];
    strftime(zone, sizeof zone, "%z", &lt);

    if(zone[0]) { // check that we got the offset from UTC
        // add the zone to the resulting string
        w += sprintf(str + w, "%.3s:", zone);
        w += sprintf(str + w, "%.2s", zone + 3);
    }
}

int main(void) {
    char buff[100];
    current_time(buff, sizeof buff);

    printf("Timestamp: %s\n", buff);
}

可能的输出:

Timestamp: 2021-11-03T10:05:06.696+01:00

符合您想要的格式:

           YYYY-MM-DDTHH:MM:SS.SSS+HH:MM

【讨论】: