在做项目中,我们经常需要获取系统的当前时间,那么如何获取呢,参见下面的代码:
/* asctime example */ #include <stdio.h> /* printf */ #include <time.h> /* time_t, struct tm, time, localtime, asctime */ int main () { time_t rawtime; struct tm * timeinfo; time ( &rawtime ); timeinfo = localtime ( &rawtime ); printf ( "The current date/time is: %s", asctime (timeinfo) ); return 0; }
输出结果为:
The current date/time is:: Thu Feb 26 11:40:19 2015
但是,有些情况下我们想分别获得年月日时分秒的值,而不是像这样得到一个整个的字符串,那么既然时间信息都存在了一个结构体timeinfo中,那么我们就先来看看这个结构体的定义吧:
struct tm { int tm_sec; // seconds of minutes from 0 to 61 int tm_min; // minutes of hour from 0 to 59 int tm_hour; // hours of day from 0 to 24 int tm_mday; // day of month from 1 to 31 int tm_mon; // month of year from 0 to 11 int tm_year; // year since 1900 int tm_wday;