int tm_sec 秒數(0~61)
int tm_min 分鐘(0~59)
int tm_hour 小時(0~23)
int tm_mday 日期(1~31)
int tm_mon 月份(0~11,從1月算起)
int tm_year 年份(從1900年算起)
int tm_wday 星期幾(日→0、一→1、二→2、以此類推)
int tm_yday 一年中的第幾天
int tm_isdst 夏令時間旗標
因此在time_t跟struct tm *格式中就存在的轉換的問題,就要利用以下兩個函數來轉換。
gmtime(); // time_t to struct tm *
mktime(); //sturct tm * to time_t
底下為兩個時間格式互相轉換的範例:
/* time_transfer.c
gmtime(): convert time_t to tm as UTC time,
mktime(): convert tm struct to time_t */
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(int argc, char **argv)
{
const char * weekday[] = {"Sun","Mon","Tue","Wed","Thu","Fri","Sat"};
const char * month[] = {"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"};
// convert struct tm to time_t
time_t t1;
struct tm tm1;
tm1.tm_hour = 12;
tm1.tm_min = 0;
tm1.tm_sec = 0;
tm1.tm_year = 2013-1900;
tm1.tm_mon = 10-1;
tm1.tm_mday = 28;
t1 = mktime(&tm1);
printf("---convert struct tm to time_t---\n");
printf("%u, %s",(unsigned int)t1,ctime(&t1));
// convert time_t to tm struct
time_t t2;
struct tm * tm2;
t2 = (time_t)1382932800;
tm2 = gmtime(&t2);
printf("---convert struct tm to time_t---\n");
printf("%s %s %d ",weekday[tm2->tm_wday],month[tm2->tm_mon],tm2->tm_mday);
printf("%02d:%02d:%02d",(tm2->tm_hour+8),tm2->tm_min,tm2->tm_sec);
printf(" %d, %u\n",(tm2->tm_year+1900),(unsigned int)t2);
return 0;
}
輸出結果:
以2013年10月28日12:00:00(UTC+8)時間為準,time_t時間為1382932800,可以看到兩者轉換的結果相同。
沒有留言:
張貼留言