我有一个字符串,其中包含自纪元以来的微秒数。如何将其转换为时间结构?
#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/