标题:C语言时间函数的使用(ISO C / POSIX / SUS...) 出处:Felix021 时间:Sat, 26 Dec 2009 18:23:20 +0000 作者:felix021 地址:https://www.felix021.com/blog/read.php?1796 内容: #include #include #include #include #define P(a, b) printf(#b ": %" #a "\n", b) #define Ps(a, c, b) P(a, (c)->b) #define alloc(name, type, n) type *name = (type *) malloc(sizeof(type) * (n)) #define allocs(name, type, n) alloc(name, struct type, (n)) int main () { time_t t1 = time(NULL); P(ld, t1); struct timeval tv1; gettimeofday(&tv1, NULL); Ps(ld, &tv1, tv_sec); Ps(ld, &tv1, tv_usec); /* * //t1 += 8 * 3600; * struct tm *tm1 = gmtime(&t1); //标准时间 */ struct tm *tm1 = localtime(&t1); //本地时间 Ps(d, tm1, tm_sec); Ps(d, tm1, tm_min); Ps(d, tm1, tm_hour); Ps(d, tm1, tm_mday); Ps(d, tm1, tm_mon+1); //0-based Ps(d, tm1, tm_year+1900); //从1900年开始, 0-based allocs(tm2, tm, 1); tm2->tm_sec = 0; tm2->tm_min = 0; tm2->tm_hour= 0; tm2->tm_mday= 1; tm2->tm_mon = 0; tm2->tm_year= 70; tm2->tm_isdst = 0; time_t t2 = mktime(tm2); //t2 += 3600 * 8; //mktime是本地时间 P(ld, t2); P(s, asctime(tm1)); //标准时间 P(s, ctime(&t1)); //本地时间 alloc(buf, char, 100); strftime(buf, 100, "%Y-%m-%d %H:%M:%S", tm1); //标准时间 P(s, buf); strftime(buf, 100, "%F %T", tm1); //标准时间, 格式和上面的一样 P(s, buf); return 0; } Generated by Bo-blog 2.1.0