time, localtime

来源:互联网 发布:收费系统源码 编辑:程序博客网 时间:2024/06/04 18:03

1、函数名: time

  头文件:time.h

  函数原型:time_t time(time_t * timer)

  功能: 获取当前的系统时间,返回的结果是一个time_t类型,其实就是一个大整数,其值表示从CUT(Coordinated Universal Time)时间1970年1月1日00:00:00(称为UNIX系统的Epoch时间)到当前时刻的秒数。然后调用localtime将time_t所表示的CUT时间转换为本地时间(我们是+8区,比CUT多8个小时)并转成struct tm类型,该类型的各数据成员分别表示年月日时分秒。

  补充说明:time函数的原型也可以理解为 long time(long *tloc),即返回一个long型整数。因为在time.h这个头文件中time_t实际上就是:

  #ifndef _TIME_T_DEFINED

  typedef long time_t; /* time value */

  #define _TIME_T_DEFINED /* avoid multiple defines of time_t */

  #endif

  即long。


2、struct tm

struct tm {
2 int tm_sec; /* seconds */
3 int tm_min; /* minutes */
4 int tm_hour; /* hours */
5 int tm_mday; /* day of the month */
6 int tm_mon; /* month */
7 int tm_year; /* year */
8 int tm_wday; /* day of the week */
9 int tm_yday; /* day in the year */
10 int tm_isdst; /* daylight saving time */
11
12 };
13
14 tm_sec The number of seconds after the minute, normally in the range 0 to 59, but can be up to 60 to allow for leap seconds.
15
16 tm_min The number of minutes after the hour, in the range 0 to 59.
17
18 tm_hour
19 The number of hours past midnight, in the range 0 to 23.
20
21 tm_mday
22 The day of the month, in the range 1 to 31.
23
24 tm_mon The number of months since January, in the range 0 to 11.
25
26 tm_year
27 The number of years since 1900.
28
29 tm_wday
30 The number of days since Sunday, in the range 0 to 6.
31
32 tm_yday
33 The number of days since January 1, in the range 0 to 365.
34
35 tm_isdst
36 A flag that indicates whether daylight saving time is in effect at the time described. The value is positive if daylight saving time is in effect, zero if it is not, and negative if the information is not available.
3.localtime是 把从1970-1-1零点零分到当前时间系统所偏移的秒数时间转换为本地时间,而gmtime函数转换后的时间没有经过时区变换,是UTC时间 
说明:此函数获得的tm结构体的时间是日历时间。
用 法: struct tm *localtime(const time_t *clock);
返回值:返回指向tm 结构体的指针.tm结构体是time.h中定义的用于分别存储时间的各个量(年月日等)的结构体.
localtime是 把从1970-1-1零点零分到当前时间系统所偏移的秒数时间转换为本地时间,而gmtime函数转换后的时间没有经过时区变换,是UTC时间 。

举例:

static char *current_time(void)
{
time_t now;
struct tm *timeptr;
static const char wday_name[7][3] = {
"Sun", "Mon", "Tue", "Wed",
"Thu", "Fri", "Sat"
};
static const char mon_name[12][3] = {
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
};
static char result[26];


time(&now);
timeptr = localtime(&now);


sprintf(result, "%.3s %.3s%3d %.2d:%.2d:%.2d %d:",
wday_name[timeptr->tm_wday], mon_name[timeptr->tm_mon],
timeptr->tm_mday, timeptr->tm_hour, timeptr->tm_min, timeptr->tm_sec, 1900 + timeptr->tm_year);


return result;
}

0 0
原创粉丝点击