如何将以微秒为单位的字符串转换为C中的struct tm?

How to convert character string in microseconds to struct tm in C?

我有一个字符串,其中包含自纪元以来的微秒数。如何将其转换为时间结构?

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

int main ()
{
    struct tm tm; 
    char buffer [80];
    char *str ="1435687921000000";
    if(strptime (str, "%s", &tm) == NULL)
        exit(EXIT_FAILURE); 
    if(strftime (buffer,80,"%Y-%m-%d",&tm) == 0)
        exit(EXIT_FAILURE);

    printf("%s\n", buffer);

    return 0;
}

编辑: 您可以简单地截断字符串,因为 struct tm 不会存储小于 1 秒的精度。

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

int main ()
{
    struct tm now; 
    time_t secs;
    char buffer [80];
    char str[] ="1435687921000000";
    int len = strlen(str);
    if (len < 7)
        return 1;
    str[len-6] = 0;                     // divide by 1000000
    secs = (time_t)atol(str);
    now = *localtime(&secs);

    strftime(buffer, 80, "%Y-%m-%d", &now);
    printf("%s\n", buffer);

    printf("%s\n", asctime(&now));
    return 0;
}

程序输出:

2015-06-30
Tue Jun 30 19:12:01 2015

您可以将微秒转换为秒,然后像这样使用localtime()

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

int main (void)
{
    struct tm *tm; 
    char   buffer[80];
    char  *str = "1435687921000000";
    time_t ms  = strtol(str, NULL, 10);

    /* convert to seconds */
    ms = (time_t) ms / 1E6;
    tm = localtime(&ms);
    if (strftime(buffer, 80, "%Y-%m-%d", tm) == 0)
        return EXIT_FAILURE;

    printf("%s\n", buffer);

    return EXIT_SUCCESS;
}

请注意,在打印日期中,微秒不存在,因此您可以忽略该部分。

将字符串转换为 time_t,然后使用 gmtime(3) 或 localtime(3)。

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

int main () {
        struct tm *tm;
        char buffer [80];
        char *str ="1435687921000000";
        time_t t;

        /* or strtoull */
        t = (time_t)(atoll(str)/1000000);

        tm = gmtime(&t);

        strftime(buffer,80,"%Y-%m-%d",tm);

        printf("%s\n", buffer);

        return 0;
}

便携式解决方案(假设 32+ 位 int)。以下不假设任何关于 time_t.

使用 mktime(),不需要将字段限制在其主要范围内。

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

int main(void) {
  char buffer[80];
  char *str = "1435687921000000";

  // Set the epoch: assume Jan 1, 0:00:00 UTC.
  struct tm tm = { 0 };
  tm.tm_year = 1970 - 1900;
  tm.tm_mday = 1;

  // Adjust the second's field.
  tm.tm_sec = atoll(str) / 1000000;
  tm.tm_isdst = -1;
  if (mktime(&tm) == -1)
    exit(EXIT_FAILURE);
  if (strftime(buffer, 80, "%Y-%m-%d", &tm) == 0)
    exit(EXIT_FAILURE);
  printf("%s\n", buffer);
  return 0;
}