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

时间:2015-06-30 18:22:17

标签: c time strftime strptime

我有一个字符串,包含自纪元以来的微秒。我怎么能把它转换成时间结构?

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

5 个答案:

答案 0 :(得分:3)

便携式解决方案(假设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;
}

答案 1 :(得分:2)

下面的解决方案怎么样?

struct tm* GetTimeAndDate(unsigned long long microsecond)
{
    unsigned long long milliseconds = microsecond/1000;
    time_t seconds = (time_t)(milliseconds/1000);
    if ((unsigned long long)seconds*1000 == milliseconds)
        return localtime(&seconds);
    return NULL;  
}

其中:

time_t

注意:如果{{1}}类型为32位长,则无法转换4G * 1000毫秒或更长时间;从UTC时间1970年1月1日00:00开始,也将考虑毫秒数。

答案 2 :(得分: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

答案 3 :(得分:0)

您可以将微秒转换为秒,并像这样使用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;
}

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

答案 4 :(得分:-1)

将字符串转换为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;
}