time_t和struct tm之间的转换

时间:2023-11-17 23:10:08

time_t到struct tm的转换:

#include <time.h>
struct tm *localtime(const time_t *timep);

struct tm到time_t的转换:

#include <time.h>
time_t mktime(struct tm *tm);

time_t timep = time(NULL);能够获得从此刻距1970-01-01 00:00:00 +0000 (UTC)时间点的秒数。

演示样例程序;

#include <stdio.h>
#include <stdlib.h>
#include <time.h> int main (int argc, char **argv)
{
int i;
time_t timer[4];
struct tm tm, *p; tm.tm_year = 2015;
tm.tm_mon = 2;
tm.tm_mday = 23;
tm.tm_hour = 8;
tm.tm_min = 22;
tm.tm_sec = 0;
for(i = 0; i < 4; i++){
timer[i] = mktime(&tm);
printf ("timer[%d] = %ld\n", i, timer[i]);
p = localtime(&timer[i]);
printf("%d-%d-%d-%d-%d-%d\n",
p->tm_year,
p->tm_mon,
p->tm_mday,
p->tm_hour,
p->tm_min,
p->tm_sec);
} return 0;
} /* ----- End of main() ----- */

by fulinux <fulinux@sina.com>

blog: blog.****.net/fulinus