linux 系统函数之 (localtime, localtime_r, strftime)
首先介绍一下localtime和localtime_r的区别。 The localtime() function converts the calendar time timep to broken-down time representation, expressed relative to the user's specified timezone.
首先介绍一下localtime和localtime_r的区别。
The localtime() function converts the calendar time timep to broken-down time representation, expressed relative to the user's specified timezone. The
function acts as if it called tzset(3) and sets the external variables tzname with information about the current timezone, timezone with the difference
between Coordinated Universal Time (UTC) and local standard time in seconds, and daylight to a nonzero value if daylight savings time rules apply during
some part of the year. The return value points to a statically allocated struct which might be overwritten by subsequent calls to any of the date and time
functions. The localtime_r() function does the same, but stores the data in a user-supplied struct. It need not set tzname, timezone, and daylight.
上面是man手册中的解释, localtime 不能同时使用,否则可能会被重写。 localtime_r则是线程安全的。
1. localtime
头文件:
#include <time.h>
函数定义:
struct tm *localtime(const time_t *timep);
功能:
把从1970-1-1零点零分到当前时间系统所偏移的秒数时间转换为本地时间,而gmtimes函数转换后的时间没有经过时区变换,是UTC时间 。
参数:
time_t 从1970-1-1时计算的utc时间。
返回值:
返回指向tm 结构体的指针.tm结构体是time.h中定义的用于分别存储时间的各个量(年月日等)的结构体.
示例:
time_t tNow =time(NULL);
time_t tEnd = tNow + 1800;
struct tm* ptm = localtime(&tNow);
struct tm* ptmEnd = localtime(&tEnd);
2. localtime_r
头文件:
#include <time.h>
函数定义:
struct tm *localtime_r(const time_t *timep, struct tm *result);
功能:
把从1970-1-1零点零分到当前时间系统所偏移的秒数时间转换为本地时间,而gmtimes函数转换后的时间没有经过时区变换,是UTC时间 。
参数:
time_t 从1970-1-1时计算的utc时间。 tm 结构体用于获取返回的时间。
返回值:
返回指向tm 结构体的指针.tm结构体是time.h中定义的用于分别存储时间的各个量(年月日等)的结构体.
示例:
time_t tNow =time(NULL);
time_t tEnd = tNow + 1800;
struct tm ptm = { 0 };
struct tm ptmEnd = { 0 };
localtime_r(&tNow, &ptm);
localtime_r(&tEnd, &ptmEnd);
3. strftime
头文件:
#include <time.h>
函数定义:
size_t strftime(char *s, size_t max, const char *format,
const struct tm *tm);
功能:
strftime() 函数根据区域设置格式化本地时间/日期,函数的功能将时间格式化,或者说格式化一个时间字符串。
参数:
示例:
struct timeval tv = {0,};
struct tm now = {0, };
char now_str[32];
gettimeofday (&tv, NULL);
localtime_r (&tv.tv_sec, &now);
strftime (now_str, 32, "%Y/%m/%d-%H:%M:%S", &now);
更多推荐
所有评论(0)