1、首先从time()函数,返回一个从1970年1月1日 00:00:00到现在的秒数
time_t time(time_t * t); 当参数为NULL时直接返回秒数,当然也会将该值写入t指针指向的地址
2、gmtime():将time函数得到的秒数转换成一个UTC时间的结构体struct tm,该结构体包含什么请自行man
通过此函数gmtime()是0时区,把UTC时间转换成北京时间的话,需要在年数上加1900,月份上加1,小时数加上8
3、同类型的函数还有localtime():得到本地时间,该函数同gmtime函数唯一区别是,在转换小时数不需要加上8了。
localtime是将时区考虑在内了,转出的当前时区的时间。但是注意,有些嵌入式设备上被裁减过的系统,时区没有被设置好,导致二者转出来的时间都是0时区的。
cpp
#include <locale.h>
#include <time.h>
#include <sys/time.h>
#include <stdio.h>
#include <cstdlib>
#define SECONDS_IN_TROPICAL_YEAR (365.24219 * 24 * 60 * 60)
int main(int argc, char *argv[])
{
time_t t;
struct tm *gmp, *locp;
struct tm gm, loc;
struct timeval tv;
t = time(NULL);
printf("Seconds since the Epoch (1 Jan 1970): %ld", (long) t);
printf(" (about %6.3f years)\n", t / SECONDS_IN_TROPICAL_YEAR);
//gettimeofday is a new system call for microsecond perception time, tv.tv_sec = time(NULL)
if (gettimeofday(&tv, NULL) == -1)
perror("gettimeofday\n");
printf(" gettimeofday() returned %ld secs, %ld microsecs\n",(long) tv.tv_sec, (long) tv.tv_usec);
gmp = gmtime(&t);
if (gmp == NULL)
perror("gmtime\n");
gm = *gmp; /* Save local copy, since *gmp may be modified by asctime() or gmtime() */
printf("Broken down by gmtime():\n");
printf(" year=%d mon=%d mday=%d hour=%d min=%d sec=%d ", gm.tm_year,
gm.tm_mon, gm.tm_mday, gm.tm_hour, gm.tm_min, gm.tm_sec);
printf("wday=%d yday=%d isdst=%d\n", gm.tm_wday, gm.tm_yday, gm.tm_isdst);
locp = localtime(&t);
if (locp == NULL)
perror("localtime\n");
loc = *locp; /* Save local copy */
printf("Broken down by localtime():\n");
printf(" year=%d mon=%d mday=%d hour=%d min=%d sec=%d ",
loc.tm_year, loc.tm_mon, loc.tm_mday,
loc.tm_hour, loc.tm_min, loc.tm_sec);
printf("wday=%d yday=%d isdst=%d\n\n",
loc.tm_wday, loc.tm_yday, loc.tm_isdst);
printf("asctime() formats the gmtime() value as: %s", asctime(&gm));
printf("ctime() formats the time() value as: %s", ctime(&t));
printf("mktime() of gmtime() value: %ld secs\n", (long) mktime(&gm));
printf("mktime() of localtime() value: %ld secs\n", (long) mktime(&loc));
exit(EXIT_SUCCESS);
}
cpp
Seconds since the Epoch (1 Jan 1970): 1694155147 (about 53.686 years)
gettimeofday() returned 1694155147 secs, 138826 microsecs
Broken down by gmtime():
year=123 mon=8 mday=8 hour=6 min=39 sec=7 wday=5 yday=250 isdst=0
Broken down by localtime():
year=123 mon=8 mday=7 hour=23 min=39 sec=7 wday=4 yday=249 isdst=1
asctime() formats the gmtime() value as: Fri Sep 8 06:39:07 2023
ctime() formats the time() value as: Thu Sep 7 23:39:07 2023
mktime() of gmtime() value: 1694183947 secs
mktime() of localtime() value: 1694155147 secs