表示时间的数据结构
表示时间戳:time_t
表示年月日时分秒:struct tm
struct tm {
int tm_sec; /* 秒,范围从 0 到 59 */
int tm_min; /* 分,范围从 0 到 59 */
int tm_hour; /* 小时,范围从 0 到 23 */
int tm_mday; /* 一月中的第几天,范围从 1 到 31 */
int tm_mon; /* 月份,范围从 0 到 11 */
int tm_year; /* 自 1900 起的年数 */
int tm_wday; /* 一周中的第几天,范围从 0 到 6 */
int tm_yday; /* 一年中的第几天,范围从 0 到 365 */
int tm_isdst; /* 夏令时 */
};
表示秒+纳秒:struct timespec
struct timespec
{
__time_t tv_sec; /* Seconds. */
__syscall_slong_t tv_nsec; /* Nanoseconds. */
};
表示秒+微秒:struct timeval
struct timeval {
time_t tv_sec; /* seconds */
suseconds_t tv_usec; /* microseconds */
};
表示时区:struct timezone
struct timezone{
int tz_minuteswest;/*和greenwich 时间差了多少分钟*/
int tz_dsttime;/*type of DST correction*/
}
获取时间
获取秒级别的时间戳:time
time函数返回1970-01-01 00:00:00 +0000时刻以来的秒数。
#include <time.h>
time_t time(time_t *t);
返回值:正常返回时间戳,同时t指针指向这个时间戳
获取微秒级别的时间戳:gettimeofday
这个函数的作用是获取当前时刻对应的时间戳和时区,时间戳是相对1970年以来的秒+微秒数。
#include <sys/time.h>
int gettimeofday(struct timeval *tv, struct timezone *tz);
返回值:执行成功,返回0,执行失败返回-1,并且置上errno
tv:指向获取到的时间,如果仅获取时区,那么tv可以传NULL;
tz:指向获取到的时区,如果仅获取时间戳,那么tz可以传NULL;
获取年月日时分秒:localtime
struct tm *localtime(const time_t *t);//传入秒数,返回年月日时分秒
获取格式化后的时间:strftime
#include <time.h>
size_t strftime(char *s, size_t max, const char *format, const struct tm *tm);
返回值:成功的话返回格式化后的时间字符串大小,失败返回0;
s:用于记录格式化后的时间字符串的缓存;
max:缓存大小;
format:格式,比如:"Now is %Y/%m/%d %H:%M:%S";
tm:待转换的时间
举例
#include <stdio.h>
#include <time.h>
int
main(int argc, char **argv)
{
time_t time1;
struct tm *time2;
char buff[1024];
time(&time1);
time2 = localtime(&time1);
if (strftime(buff, sizeof(buff), "Now is %Y/%m/%d %H:%M:%S", time2)) {
printf("time: %s\n", buff);
}
else {
perror("strftime failed.\n");
return -1;
}
return 0;
}
4500

被折叠的 条评论
为什么被折叠?



