UTC:
1970年1月1日0点至今的秒数。(本文不考虑闰秒)
本地时间:
UTC对应0时区,北京位于东八区,时间为UTC+8h。
#include <stdio.h> #include <time.h> int main(int argc, char **argv) { time_t utc_timestamp = time(NULL); printf("utc timestamp is: %ld ", utc_timestamp); struct tm *utc_tm = gmtime(&utc_timestamp); printf("utc time is: %s ", asctime(utc_tm)); struct tm *local_tm = localtime(&utc_timestamp); printf("local time is: %s ", asctime(local_tm)); printf("local time is: %s ", ctime(&utc_timestamp)); return 0; }
相关API:
// 返回UTC时间戳 time_t time (time_t* timer); // Convert time_t to tm as UTC time struct tm * gmtime (const time_t * timer); // Convert time_t to tm as local time struct tm * localtime (const time_t * timer); // Convert tm structure to string char* asctime (const struct tm * timeptr); // Convert time_t value to string, in terms of local time char* ctime (const time_t * timer);
tm结构:
struct tm { int tm_sec; /* seconds after the minute [0-60] */ int tm_min; /* minutes after the hour [0-59] */ int tm_hour; /* hours since midnight [0-23] */ int tm_mday; /* day of the month [1-31] */ int tm_mon; /* months since January [0-11] */ int tm_year; /* years since 1900 */ int tm_wday; /* days since Sunday [0-6] */ int tm_yday; /* days since January 1 [0-365] */ int tm_isdst; /* Daylight Savings Time flag */ long tm_gmtoff; /* offset from CUT in seconds */ char *tm_zone; /* timezone abbreviation */ };
time_t一般用long或者long long表示。