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

标签 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;
}

最佳答案

可移植解决方案(假设 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;
}

关于c - 如何将以微秒为单位的字符串转换为C中的struct tm?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31145629/

相关文章:

python-3.x - pandas to_datetime 无法将非零填充字符串转换为日期时间

C 递归程序无法通过 GCC 编译

c - 将指针的值分配给其他指针时,只读位置分配错误?

javascript - setInterval 改变 Action 下的速度

c++ - Unix 函数 gmtime_r 的 Windows 等价物是什么?

在 OSX 上编译的 ctime 和时间警告

python-3.x - 如何在Pandas中一次将多列数据类型格式转换为另一种数据类型格式,而又不提及列名称?

c - 动态声明数组sizeof

c - fscanf 和 sscanf 的速度

c++ - 在 C++ 中重用 strftime