2010-10-14 103 views
0

我有一段时间以UTC格式存在的时间作为一些数据的时间戳,现在我想将它转换为以下格式: month 1-12 Day 1- 31 24小时格式0-23 分钟0-59 第二0-59 一秒纳秒0-999,999,999将UTC转换为天,小时分钟等C

现在纳秒显然可以设置为0作为它不需要是精确的。

这样做的最佳方法是什么?我见过大量的例子,但它们令人困惑,似乎没有用于转换任意日期,它们仅用于转换当时的确切时间。

+0

任何严格UTC函数将返回[0,60]为秒(60是一个闰秒),然而,许多实现忽略此。请注意你选择的任何实现。 – Thanatos 2010-10-19 00:20:14

回答

0

你在这里。注意注释行

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

int main(void) { 
    char buf[512]; 
    long stamp = 1287055578; 
    struct tm x; 
    time_t cstamp = stamp;  /* 1 */ 
    x = *gmtime(&cstamp);  /* 2 */ 

    sprintf(buf, "month %d Day %d 24 Hour format %d minute %d second %d " 
       "subsecond nanoseconds 0", 
       x.tm_mon + 1, x.tm_mday, x.tm_hour, x.tm_min, x.tm_sec); 

    printf("%s\n", buf); /* long converted to string */ 
    return 0; 
} 

1)gmtime需要time_t*类型的值,所以我隐式转换的longtime_t并且在下一步骤

2)gmtime返回一个指向一个struct tm传递地址目的。取消引用该指针和复制对象到我的本地x变量

相反的gm_time,您可能需要使用localtime并有库函数处理时区和夏令时的问题。

+0

很好的答案,谢谢。 – rolls 2010-10-19 00:12:00

0

感谢您的答案大家,我结束了做这种方式

long UTCInSeconds = ... 

struct tm * local; 
local = localtime(UTCInSeconds); 

Month = local->tm_mon + 1; 
Day = local->tm_mday; 
Year = local->tm_year + 1900; 
Hour = local->tm_hour; 
Minute = local->tm_min; 
Second = local->tm_sec; 
相关问题